我正在使用Spotify API
开发播放列表生成器。我在React中重构代码,对异步调用提升状态有些困惑。
在我的App component
中,我有一个login
函数,该函数对用户进行身份验证,然后使用用户信息更新状态。我将此通过nav component
传递给执行该功能的按钮组件,然后使用用户信息更新状态。我需要使用此用户信息将登录按钮重新呈现为用户的姓名和照片。
class App extends Component{
//login function
//loginUser(){}
return(
<NavBar loginClicked={this.loginUser} loggedIn={this.state.loggedIn} user={this.state.curUser ? this.state.curUser: undefined}/>
)
}
class NavBar extends Component{
render(){
return (
<nav>
<div className="logo" aria-label="sign in">
<h1><a href="index.html">Moment Music</a></h1>
</div>
<SignIn loginClicked = {this.props.loginClicked} user={this.props.user ? this.props.user: undefined} loggedIn = {this.props.loggedIn} />
</nav>
);
}
}
class SignIn extends Component{
componentWillReceiveProps(nextProps){
console.log(nextProps);
return this.setState({nextProps});
}
render(){
console.log(this.state.user)
return(
<div className='top-right'>
{this.state.loggedIn ?
( //<div className="logged-in" id='logged-in' aria-label="logged in">
<div className="logged-in" id='profile-nav-bar'>
<img className = "profile-img" id='profile-img' src={this.state.user.profileImg}/>
<h2 id='profile-name'>{this.state.user.username}</h2>
</div>)
//</div>)
:
(<div onClick={this.props.loginClicked} className="sign-in" id="sign-in" aria-label="sign in">
<a className="btn btn-primary">Log in with Spotify</a>
</div>)
}
</div>
)
}
}
我可以使用componentWillRecieveProps
来更新状态,但是不会传递给SignIn
的render方法。
感谢您的帮助。
答案 0 :(得分:1)
您不应在子组件中将props设置为状态。登录中不需要componentWillReceiveProps。如果SignIn组件属性将更改,则将执行render方法。反应检查状态和道具的更改以重新渲染组件。在SingIn中使用this.props代替this.state
如果在子组件中使用loginClicked方法,并且在函数中引用此方法,则应使用适当的上下文进行调用。因此,最好的方法是使用箭头功能:loginUser = () => { // your function here }