将道具传递到顶层组件中的状态

时间:2020-07-17 06:38:23

标签: reactjs components state react-props

我正在尝试使用子组件中的handleUpdate函数将道具传递给顶层组件,并使用这些道具值更新状态。到目前为止,我在控制台日志中看不到道具。我认为我没有传递正确的论点。我四处碰碰,被卡住了。有人可以协助和解释他们的推理吗?

子组件中的

handleUpdate函数:

search = async (word) => {

        try{
            // var word = this.state.word.trim();
            const data = await MerriamAPI.getWordInfo(word);
            
            if (data){
                this.props.handleUpdate({
                    word: word,
                    info: data,
                    versions: data[0].meta.stems,
                    shortdef: data[0].shortdef[0],
                    partOfSpeech: data[0].fl,
                    pronunciation: data[0].hwi.prs[0].mw, 
                }, 
            }
            else{
                console.log('No Definition Found')
            }
        }
        catch{
            this.setState({error: 'No Definition Found'})
        }
        console.log(this.props)
    }

父组件:

class App extends Component {

  state = {
    redirect: {},
    word: '',
    error: '',
    info: [],
    partOfSpeech: [],
    versions: [],
    shortdef: "",
    pronunciation: "",
  }
  

  setRedirect = redirect =>
    this.setState({redirect})


  handleUpdate = (props) => 
    this.setState({word:this.props})


render() {
    return (
      <>
        <Route 
          render={ routeProps => <Redirector redirect={this.state.redirect} setRedirect={this.setRedirect} {...routeProps} />}
        />
        <header>
          <nav>
            <Link to='/'>My Dictionary</Link>
          </nav>
        </header>

        <main>
        <Route
            render = { routeProps =>
              !routeProps.location.state?.alert ? '' :
              <div>
                { routeProps.location.state.alert }
              </div>
            }
          />
          <Switch>
            <Route exact path="/" render={ routeProps => <Home handleUpdate={this.handleUpdate} {...routeProps} />} />
            <Route exact path="/definition/:word" render={ routeProps => <GetWordContainer word={this.state.word} {...routeProps} />} />
          </Switch>
        </main>
      </>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:1)

如果我可以解密您的部分片段,则handleUpdate中的App似乎访问了错误的“道具”对象,即this.props的{​​{1}}而不是传递的{ {1}}函数的参数。

解决方案

将功能参数更改为除“ props”之外的其他参数以消除混淆,App是一个不错的选择,它还允许您使用对象速记分配。

props

根据您传递给word和状态对象的对象形状,我猜想您更可能希望在对象中散布而不是全部分配给handleUpdate = word => this.setState({ word });

handleUpdate
相关问题