【问题标题】:react-redux) mapStateToProps works, but sending local(?) props to child component returns undefined.react-redux) mapStateToProps 有效,但是将本地(?)道具发送到子组件返回未定义。
【发布时间】:2018-10-03 12:35:28
【问题描述】:

您好,我在将道具传递给子组件时遇到了一些问题。 问题是,将全局状态作为道具发送到子组件可以正常工作,但我无法将本地道具发送到子组件。

我不知道为什么,但它返回 undefined。

    const mapStateToProps =(state)=>{
    return state.itemInfo
}

export class ItemInformationContainer extends React.Component{
    componentWillUnmount(){
        store.dispatch(hideItemInfo());
    }
    handleBackToList = (e)=>{
        console.log('back please');
        store.dispatch(hideItemInfo());
    }
    render(){
        return(
            <WrappedItemComponent backToList={this.handleBackToList} {...this.props}/>
        )
    }
}

export const ItemInformation =(props)=>{
    console.log(props);
    return(/*some codes*/
    )
}
const WrappedItemComponent = connect(mapStateToProps)(ItemInformation);

在 ItemInformation 组件中,我使用了 console.log(props) 来检查展示组件是否正在从父组件获取 backToList 道具。

但结果是

{backToList: undefined, content: {…}, type: "country", status: "show", dispatch: ƒ} backToList: 未定义

backToList 未定义。

我真的需要这个道具。我如何解决它?

请忽略组件WillUnmount。如果 handleBackToList 可以正常工作,那么该生命周期方法将从代码中删除。

【问题讨论】:

  • 一切正常! codesandbox.io/s/31893rzno1
  • @HardikModha 这很奇怪。我在我的代码中未定义.. 在你的代码中,我看到你在 backToList 中做警报。但是,我看不到任何警报
  • 我还没有调用这个函数! :) 更新:现在它会显示警报!
  • 看看代码有没有错误。尝试运行 jshint。
  • @kustkust 请提供stackoverflow.com/help/mcve,这样可以复制问题。我希望您的实际代码与您发布的不同。

标签: reactjs react-redux


【解决方案1】:

嗯,这是我愚蠢而愚蠢的错误。

该错误是由于祖父组件将相同的道具传递给父组件而引起的。

所以代码的结构是这样的:

Countries 组件 -> ItemInformationContainer 组件 -> ItemInformation 组件

我很愚蠢,在国家组件中做了这样的事情

return(
      <section id="ItemResult">
            <ItemInformationContainer backToList={this.backToList} content={this.state.content}/>
                    </section>
      )

将 backToList 道具传递给子组件,并且国家组件中没有 backToList 功能 当然 backToList 是未定义的,并且 ItemInformationContainer 也未定义,据我所知。

所以,我刚刚删除了国家组件中的 backToList 道具并且工作正常。

【讨论】:

  • propTypes 救援 ;) - {...this.props} 覆盖了之前的
猜你喜欢
  • 2021-11-06
  • 2019-01-15
  • 2021-09-01
  • 2016-09-15
  • 1970-01-01
  • 2016-09-19
  • 2019-09-20
  • 1970-01-01
  • 2018-02-03
相关资源
最近更新 更多