将道具传递给顶级组件中的状态

Passing props to state in top level component

我正在尝试使用我的子组件中的 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;

如果我能破译你的部分片段,App 中的 handleUpdate 似乎访问了错误的“props”对象,即 Appthis.props 而不是将 props 参数传递给函数。

解决方案

将函数参数更改为“props”以外的参数以消除混淆,word 是一个不错的选择,它允许您还使用对象 shorthand 赋值。

handleUpdate = word => this.setState({ word });

根据您传递给 handleUpdate 的对象形状和您的状态对象,我猜测您更有可能希望散布对象而不是将其全部分配给 this.state.word

handleUpdate = values => this.setState({ ...values });