【问题标题】:Passing props to state in top level component将道具传递给顶级组件中的状态
【发布时间】:2020-11-06 22:24:48
【问题描述】:

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

【问题讨论】:

    标签: reactjs components state react-props


    【解决方案1】:

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

    解决方案

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

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

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

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

    【讨论】:

    • 太棒了,也谢谢你的解释!我需要的是后者。
    • @Elizabeth 太棒了!谢谢,如果您对解释表示赞赏,请随时投票。
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2019-11-16
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    相关资源
    最近更新 更多