首页 > 解决方案 > 事件渲染前如何获取道具

问题描述

我是 React 的初学者,在渲染孩子之前从父母那里获取道具有问题。 组件连接

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

但是当我点击按钮时在 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(){...}

标签: javascriptreactjsreact-hooksreact-props

解决方案


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

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

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

但是,为什么不直接使用fetchQuery中的道具,而不是将其设置为 state 呢?

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

推荐阅读