我使用兩個異步函數來模擬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>
這是輸出
這裏倉庫https://github.com/wilcus/stackoverflow-question/
'Promise.all'? –