【问题标题】:Get default state value by receiving prop data - React通过接收道具数据获取默认状态值 - React
【发布时间】:2018-05-01 08:58:07
【问题描述】:

我是react.js 的新手。 我想通过接收props.user.following_status 来获取状态following_status 的默认值。

我将用户对象 (user = { following_status: 'following', id:123 }) 传递给 ReactionButton 组件。 ReactionButton 组件是这样的:

class RelationButton extends React.Component {

  constructor(props){
    super(props);
    console.log(props.user.following_status) #  undefined!!!

    this.state = {
      following_status: props.user.following_status
    }
...
    render() {
       if (this.state.following_status == 'following') {
         <UnFollowBtn/>
       } else {
         <FollowBtn/>
       }
    }

RelationButtonUserCardHeader 组件调用。

const UserCardHeader = (props) => {
  const user = props.user;
  return(
    <header className="user-card--full__header">
      <RelationButton user={user}></RelationButton>
    </header>
  )
}

我不明白为什么console.log(props.user.following_status) 返回undefined。我用谷歌搜索了很多这样的网站:

这些答案建议

class FirstComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          x: props.initialX
        };
    }
}

但这对我不起作用。

如果我在上面的代码中添加componentWillReceiveProps

  componentWillReceiveProps(props){
    console.log(props.user.following_status)   #=> "following"
    this.setState({following_status: props.user.following_status})
  }

一切正常。但是我认为这是一个奇怪的解决方案,有时不起作用。为什么我无法在constructor(props) {} 部分接收对象道具?

【问题讨论】:

  • 你必须显示谁在渲染RelationButton
  • @MilosMosovsky 谢谢我添加到问题中
  • 你能不能尝试在console.log('render')里面RelationButton渲染方法,看看它是否没有被调用两次?也许你做了奇怪的包装或者用户是异步的,因此它在 mount 中不可用,但 componentWillReceiveProps 将在每次道具更新时被调用
  • 显示你如何使用UserCardHeader
  • @MilosMosovsky 输出是 render render 是的,实际上调用了两次

标签: javascript reactjs react-props


【解决方案1】:

如果没有完整的代码,我们无法判断出了什么问题,但很明显following_status 与组件异步出现,这就是为什么无法在构造函数中立即访问的原因。

要以某种方式修复它,您可以在 componentDidUpdate 中检测道具是否已更改并相应地重置状态。

class RelationButton extends React.Component {

  constructor(props){
    super(props);
    console.log(props.user.following_status) #  undefined!!!

    this.state = {
      following_status: props.user.following_status
    }
  }

  componentDidUpdate(prevProps) {
    if(prevProps.user.following_status !== this.props.user.following_status) {
      this.setState({ following_status: this.props.user.following_status })
    }
  }

  render() {
     // you forgot about return statements :
     if (this.state.following_status == 'following') {
       return <UnFollowBtn/>
     } else {
       return <FollowBtn/>
     }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 2020-03-17
    • 2017-05-14
    • 2019-12-27
    相关资源
    最近更新 更多