什么是呈现异步调用两个值更新的正确方法?
问题描述:
我使用两个异步函数来模拟AJAX什么是呈现异步调用两个值更新的正确方法?
- 一个变量来获得一个组合框的选项
- 其他变量获得一个组合框
值但当页面加载组合框卡住原始值“0”并且不更新。
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
App.js
import React, { Component } from 'react';
const Select = ({ options=[], keyOfName, placeholderMessage, defaultValue="-1" }) => {
return (
<select required defaultValue={defaultValue}>
<option disabled value="-1">{placeholderMessage}</option>
{
options.map(function (option, index) {
return (
<option key={index} value={index}>
{option}
</option>
);
})
}
</select>
)
}
class Bug extends Component {
constructor(){
super();
this.state = {index: 0}
let self = this;
setTimeout(()=>{
console.log("before setState :" + this.state.index);
self.setState({index: 1});
console.log("after setState :" + this.state.index);
}, 2000);
}
render(){
return (
<Select
options={this.props.options}
defaultValue={this.props.options ? this.state.index : -1}
placeholderMessage="Seleccione una Cuenta"
/>
)
}
}
class App extends Component {
constructor(){
super();
this.state = {options: []};
let self = this;
setTimeout(()=>{self.setState({options: ["ji", "xo"]})}, 2000);
}
render() {
return (
<div>
<Bug options={this.state.options}/>
</div>
);
}
}
export default App;
的index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
这是输出
答
你的问题是,你正在使用的不是defaultValue
作为value
中的参数标签<select/>
'Promise.all'? –