【问题标题】:props not defined in render but value seen in return of render for the first time component is mounted未在渲染中定义的道具,但在第一次安装组件时返回渲染时看到的值
【发布时间】:2016-07-11 17:31:56
【问题描述】:

我将 React 与 react-router 和 react-redux 一起使用。 当一个组件挂载时,我会派发从数据库中获取数据。 我的父组件有这个

const TopComp = React.createClass({  
 componentWillMount(){
     this.props.dispatch(getData(this.params.id))
 },
 render() {
  <ChildComp data={this.props.data} />
 }
})
function mapStateToProps(state){
    return {data:state.data}
 }
export default connect()(TopComp)

我的子组件如下所示:

 const ChildComp = React.createClass({
 getInitialState() {
  console.log(this.props.data) 
 //empty for the first time but gets data other times
 }
 render(){
 console.log(this.props.data) //prints undefined
 return(
  {this.props.data} //gives the data
 ) 
 }
 })

还有我的 TopComp 更新,点击它的父组件上的链接。它接收不同的 params.id 并为每个参数获取数据。

【问题讨论】:

    标签: reactjs react-router redux react-redux react-router-redux


    【解决方案1】:

    你没有通过你的mapStateToProps 函数来连接......所以我很惊讶你甚至可以访问你的状态数据。

    export default connect(mapStateToProps)(TopComp) 
    

    至于 this.props.data 打印未定义 --> 你只在父组件挂载时获取数据 - 然后执行 XHR 请求等,所以首先子组件中的 this.props.data 将是未定义的,因为请求尚未完成。

    【讨论】:

    • 实际上我在这里输入时错过了 mapStateToProps。我肯定会遇到您提到该组件在初始 render() 中没有收到道具的问题。你能告诉我如何以不同的方式完成,所以我将在 Child 中获得初始渲染中的道具
    猜你喜欢
    • 2023-01-14
    • 2021-11-22
    • 1970-01-01
    • 2020-10-04
    • 2020-07-17
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多