我使用两个异步函数来模拟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>
这是输出
答案 0 :(得分:1)
您的问题是,您使用defaultValue
代替value
作为标记<select/>
答案 1 :(得分:1)
defaultValue
仅设置一次值。您希望使用value
进行受控输入。从React文档中查看this example。