如何在事件渲染前获取道具

How to get props before event Render

我是 React 的初学者,在呈现 child 之前从 parent 获取道具时遇到问题。

如您所见,我有一个编辑器组件,它将字符串作为道具发送到按钮。在有人单击按钮(onClick 事件)之前收集的位置,然后使用道具(来自编辑器)更新状态并将其作为道具发送到 DataTable 其中方法 componentWillReceiveProps 将道具作为获取请求发送.

! 但是当我单击按钮时 ! 在 DataTable 组件从按钮接收道具之前调用 fetch。我知道 child 在 parent 之前被称为 现在该怎么办?我迷失在其中。

这是一些代码
按钮

    componentWillReceiveProps(nextProps, nextContext) {
        if(nextProps.queryFromEditor !== this.props.queryFromEditor){
            this.setState({queryFromEditorString: nextProps.queryFromEditor.join(' ')});
        }
    }

    submitData= () =>{
        this.setState({
            buttonState: !this.state.buttonState,
            queryFromEditorString: this.state.queryFromEditorString,
        });
        //console.log('Button: '+ this.state.queryFromEditorString)
    }
render(){
      return(
               <div>
                  <div className="submit">
                      <input onClick={this.submitData} id="querySend"
                             type="submit"
                             value="Submit query"
                              />
                  </div>
<DataTable
                queryFromEditorString = {this.state.queryFromEditorString}
                buttonState = {this.state.buttonState}/>
             </div>
              )
}



DataTable

componentWillReceiveProps(nextProps, nextContext) {
        if(nextProps.buttonState !== this.props.buttonState){
            this.setState({queryFromEditor: nextProps.queryFromEditorString});
            console.log('Component: '+this.state.queryFromEditor)
            this.fetchQuery()
        }
    }


    fetchQuery(){
        fetch('/api/query',
            {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ content: this.state.queryFromEditor})
            })
            .then(res => res.json())
            .then(qo =>{ this.setState({queryOutput: qo})
                console.log('Table fetch: '+JSON.stringify(qo))
            })
    }

    componentDidMount(){

        //Fetching number of affected and changed rows
        fetch('/api/update')
            .then(res => res.json())
            .then(rows => {this.setState({rows: rows})
            console.log(rows)
            });

        //Fetching output from user query
        this.fetchQuery()

    }

render(){...}

this.setState 是异步的,意味着它不会立即更新组件。

如果你真的想从 props 更新状态,我建议改用 getDerivedStateFromProps。 另一种解决方案是在 setState 的回调中调用 this.fetchQuery() 以确保更新完成,如下所示:

this.setState({queryFromEditor: nextProps.queryFromEditorString}, () => {
  console.log('Component: '+this.state.queryFromEditor)
  this.fetchQuery()
});

但是,为什么不直接使用fetchQuery中的props,而不是设置成state呢?

body: JSON.stringify({ content: this.props.queryFromEditor})