反应:等待状态更新

时间:2018-04-11 17:30:42

标签: reactjs

在我的页面上,我有两个<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();
}

2 个答案:

答案 0 :(得分:2)

在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);
    }
}

答案 1 :(得分:0)

如果组件收到的所有道具都来自此组件,那么您需要做的就是确保除非您需要,否则此组件不会更新。您可以使用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() {
    ....
}
相关问题