反应:等待状态更新



在我的页面上,我有两个<select>元素。第二个取决于第一个。第一个包含建筑物编号,该建筑物中的第二个房间。当我改变建筑物时,我也想更换房间,但状态仍然具有旧建筑物状态。例如,在第一个选择中,我有建筑物 [A, B, C]。一开始第一个选择设置在A上,第二个选择的房间是正确的,但是将建筑物更改为B后,房间仍然为A,然后将建筑物更改为C,房间为B。

jsx 代码的一部分:

<div className="row">
    <div className="col">
       <label> Budynek: </label>
    </div>
    <Building onChangeHandler={event => this.onChangeHandler(event)} />
</div>
<br />
<div className="row">
   <div className="col">
       <label> Sala: </label>
   </div>
   <Room building={this.state.building} />
</div>


<select>中选择另一个值后更改状态的方法

onChangeHandler(event) {
    this.setState({ building: event.target.value }, () => {});
}

我知道 setState(( 不会立即更新状态。但是如何等到它更新?
<Room/>组件正在更新componentWillReceiveProps()


update

fetchRooms() {
    fetch(`http://localhost:3000/rooms/building/${this.props.building}`)
        .then((res) => {
            return res.json()
        })
        .then(data => {
            let rooms = '';
            data.forEach(room => {
                rooms += `
                    <option value="${room.number}">${room.number}</option>
                `
            })
            this.setState({ rooms });
        })
}
componentDidMount() {
    this.fetchRooms();
}
componentWillReceiveProps(){
    this.fetchRooms();
}

在 componentWillReceiveProps 中,你调用的是 this.fetchRooms,但是在 fetchRooms 函数中,你仍然使用 this.props,因此不会检索到新数据。此外,在调用函数之前,还必须进行比较

fetchRooms(props) {
    const { building } = props || this.props;
    fetch(`http://localhost:3000/rooms/building/${building}`)
        .then((res) => {
            return res.json()
        })
        .then(data => {
            let rooms = '';
            data.forEach(room => {
                rooms += `
                    <option value="${room.number}">${room.number}</option>
                `
            })
            this.setState({ rooms });
        })
}
componentDidMount() {
    this.fetchRooms();
}
componentWillReceiveProps(nextProps){
    if(nextProps.building !== this.props.building) {
       this.fetchRooms(nextProps);
    }
}
<</div> div class="one_answers">

如果您的组件接收的所有 props 都来自此组件,那么您需要做的就是确保此组件不会更新,除非您希望它更新。你可以为此使用 shouldComponentUpdate。

像这样的东西。(我还没有测试过这个,只是一个我认为可以工作的想法。

constructor(props){
    super(props)
    this.state = { 
        shouldUpdate: false
    }
}
onChangeHandler(event) {
    this.setState({ building: event.target.value }, () => {
        shouldUpdate: true
    });
}
shouldComponentUpdate(nextProps, nextState){
    if(nextState.shouldUpdate){
        return true;
    }
    return false;
}
render() {
    ....
}

最新更新