【问题标题】:React: How do I pass props to state component?React:如何将道具传递给状态组件?
【发布时间】:2019-10-14 12:25:54
【问题描述】:

需要帮助将状态作为道具传递给另一个状态组件。我对 React 很陌生,我不确定我做错了什么。当我在 Timer 组件中使用 console.log 时,它显示未定义,但是当我在 Main 组件中使用 console.log 时,它完美地显示了对象。

class Main extends React.Component {
  constructor() {
      super()
      this.state = {
          isLoaded: false,
          itemsP:{}
      }
  }

  componentDidMount() {
    fetch("https://api.spacexdata.com/v3/launches/next")
        .then(response => response.json())
        .then(
            (resData) => 
                this.setState({
                     isLoaded: true,
                     itemsP: resData
                 })
        )
}



render() {
   console.log(this.state.itemsP) //this will console.log the object from the api

    return (           
        <main>
           <Timer nextLaunch={this.state.itemsP} />
        </main>

    )
}
}

//Timer component

class Timer extends React.Component{
constructor(props) {
    super(props)
    this.state = {
        nextDate: props.nextLaunch.launch_date_utc             
    }
}

render() {
   console.log(this.state.nextDate)  //will console log UNDEFINED why is this?

    return (    
      <div>
        //display something....
      </div>
    )
}
}

here 是我用作参考的 API 的链接。

【问题讨论】:

  • 你可以显示你的Timer组件

标签: javascript reactjs


【解决方案1】:

@tlrmacl 可能已经在那里回答了。它缺少 this 关键字。从理论上讲,您可能仍在将初始值分配给状态。

这是由于反应生命周期的工作原理

在您的 componentDidMount() 上,您在 jsx 挂载到 DOM 后调用 setState。 this.state.itemsP 被赋予初始值{} 然后在挂载后,它将从comopnentDidMount() 接收新值

在您的Timer 组件中,您将this.props.nextLaunch 的第一个值分配给一个新状态。它没有机会更新值。而不是这样做:

this.state = {
        nextDate: props.nextLaunch.launch_date_utc             
}

直接使用props.nextLaunch.launch_date_utc

console.log(props.nextLaunch.launch_date_utc)

有关更多信息,请查看 Dan Abramov here 的这条推文

【讨论】:

  • 是的,谢谢!所以我最初的想法是在父组件中设置状态会自动“重启”子 Timer 组件并再次设置状态。在这种情况下,更新子组件中的状态的“最佳实践”是什么?
【解决方案2】:

从你的父组件你将值传递为nextLaunch 不要忘记在你的父组件构造函数中调用 props

 constructor(props) {
    super(props);
    this.state = {
      isLoaded: false,
      itemsP: 'myValue'
    }
 }

<Timer nextLaunch={this.state.itemsP} />

所以在你的计时器组件中打印你的值你必须以这种方式调用你的道具this.props.nextLaunch

class Timer extends React.Component {
  render() {
    return <p>My nextLaunch data are {this.props.nextLaunch}.</p>;
  }
}

希望对你有帮助

【讨论】:

    【解决方案3】:
    //Timer component
    
    class Timer extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            nextDate: this.props.nextLaunch.launch_date_utc             
        }
    }
    

    您需要 this.props 而不是构造函数中的 props

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 2020-10-08
      • 2019-11-16
      • 2018-08-01
      • 2018-11-05
      • 2020-12-19
      • 2018-08-13
      相关资源
      最近更新 更多