我正在实现一个带有值和onChange的选择标记,onChange会触发一个redux动作并更新在select标记的选项中使用的状态(因此组件会随着状态的更新而更新)
我尝试正常地使用回调函数更新状态。这无济于事
import React from "react";
import { connect } from "react-redux";
export class SelectDestination extends React.Component {
constructor(props)
{
super(props);
this.state={defaultval:''}
}
onSelectChange = event => {
let val=event.target.value
this.setState({defaultval:event.target.value},function(){this.props.onSelectChange(val)})
};
render() {
let options = this.props.state.planets.filter((x)=>this.props.state.vistedDestinatons.indexOf(x.name)===-1);
console.log(options)
return (
<React.Fragment>
{
<select value={this.state.defaultval} onChange={this.onSelectChange} name="onselect">
{options.map(x => (
<option value={x.name.toString()}>{x.name}</option>
))}
</select>
}
</React.Fragment>
);
}
}
const mapStateToProps = state => {
return {
state: state
};
};
const mapDispatchToProps = dispatch => {
return {
onSelectChange: payLoad =>
dispatch({ type: "SELCT_CHNG", payload: payLoad })
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SelectDestination);
我希望状态必须反映在select标签中。在react-dev-tools中打开后,我可以看到状态正在更新。