为什么当我通过一个已定义的状态时我的道具是未定义的?

Why is my props undefined when i passed a defined state through?

我正在尝试将数据传递给子组件,但我一直收到未定义的道具。我认为当我在父组件中设置状态时可能有问题。我不应该使用 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} />

    )
  }
}

问题是您的承诺可能不会 return 在 componentWillMount 完成并调用 render 之前。所以 products 还不存在。你可以这样做:

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

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

你可以这样做

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