在异步 API 请求后更新子组件中的状态 - React 中的 Spotify API

Updating state in child component after asynchronous API request - Spotify API in React

我正在使用 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 的渲染方法。

提前感谢您的帮助。

您不应该将道具设置为子组件中的状态。您在 SignIn 中的 componentWillReceiveProps 是不必要的。如果 SignIn 组件 props 发生变化,则将执行 render 方法。反应检查状态和道具的更改以重新渲染组件。在 SingIn 中使用 this.props 代替 this.state

如果您在子组件中使用 loginClicked 方法并在函数中引用此方法,您应该使用适当的上下文进行调用。所以,最好的方法是使用箭头函数:loginUser = () => { // your function here }