【发布时间】: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/>
}
}
RelationButton 被UserCardHeader 组件调用。
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