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

时间:2020-03-05 13:20:50

标签: javascript reactjs react-hooks react-props

我是React的初学者,在渲染孩子之前,我有从父母那里获得道具的问题。 Component connection

如您所见,我具有编辑器组件,该组件将字符串作为道具发送到按钮。在哪里收集直到有人单击按钮(onClick事件),然后使用props(从Editor)更新状态,并将其作为props发送到DataTable,其中是方法 componentWillReceiveProps ,将props作为获取请求发送。 >

但是,当我单击按钮时,将在DataTable组件从按钮接收道具之前调用fetch。我知道孩子被叫是在父母之前要做什么?我迷失了它。 ?

这是一些代码
按钮

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



数据表

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(){...}

1 个答案:

答案 0 :(得分:0)

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

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

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

但是,为什么不直接在 fetchQuery 中使用道具,而不是将其设置为状态?

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