【问题标题】:Why is my props undefined when i passed a defined state through?当我通过定义的状态时,为什么我的道具未定义?
【发布时间】:2017-02-19 07:37:25
【问题描述】:

我正在尝试将数据传递给子组件,但我不断收到未定义的道具。我认为当我在父组件中设置状态时可能有问题。我不应该使用 componentWillMount 吗?

export default class AllItems extends Component {
  constructor () {
    super()
    this.state=({ user: cookie.load('user')})
    this.httpHandler = axios.create({
      baseURL: 'http://localhost:3000/',
      headers: {
        'Authorization': this.state.user.token
      }
    })
  }

  componentWillMount() {
    this.httpHandler('/products/')
    .then(function (response) {
      this.setState({ winks: response.data.data})
      console.log(this.state.winks)
    }.bind(this))
  }
  render() {
    return (

              <Winks products={this.state.winks} />

    )
  }
}

【问题讨论】:

    标签: reactjs ecmascript-6 components react-jsx


    【解决方案1】:

    问题是在componentWillMount 完成和render 被调用之前你的promise 可能不会返回。所以products 还不存在。你可以这样做:

    render() {
      if (this.state.winks) {
        return (<Winks products={this.state.winks} />)
      } else {
        return (<div>No Winks yet</div>);
      }
    }
    

    【讨论】:

      【解决方案2】:

      问题是你没有眨眼的初始状态由于你依靠ajax调用来设置眨眼的状态,ajax调用将异步发生,然后它将在api调用之前执行渲染函数完成导致 this.state.winks 最初未定义。

      你可以这样做

      render() {
        let content = this.state.winks ? <Winks products={this.state.winks} /> : <div/>
        return <div> {content} </div>
      

      【讨论】:

        猜你喜欢
        • 2017-04-07
        • 1970-01-01
        • 2018-10-27
        • 1970-01-01
        • 2016-10-27
        • 1970-01-01
        • 2019-07-12
        • 2021-04-28
        • 2019-11-12
        相关资源
        最近更新 更多