【发布时间】:2020-02-18 03:24:42
【问题描述】:
我是 React 新手,如果这太基础了,请见谅。
我有一个应用程序,它有一个 api 令牌,需要作为 props 传递给许多组件,但在父组件 App.jsx 中没有获取。
我的令牌是在子组件 Spotify.jsx 中获取的,所以我尝试这样实现:
- 在父组件中使用
this.state.spotifyToken = ''设置我的令牌 - 创建一个回调函数
onConnectWithSpotify(),也在Parent处 - 将此回调函数作为
props传递给子组件 - 调用函数并将
this.state.spotifyToken更新回Parent
我的组件:
App.jsx(父组件):
class App extends Component {
constructor() {
super();
this.state = {
spotifyToken: ''
};
this.onConnectWithSpotify = this.onConnectWithSpotify.bind(this);
};
// --> callback
onConnectWithSpotify(token){
this.setState({ spotifyToken: token});
}
render() {
return (
<div>
<Route exact path='/' render={() => (
<SpotifyAuth
onConnectWithSpotify={this.onConnectWithSpotify}
spotifyToken={this.state.spotifyToken}// --> pass here
/>
)} />
</div>
)
}
Spotify.jsx(子组件):
handleRedirect(event) {
const params = this.getHashParams();
const access_token = params.access_token;
console.log(access_token); // --> this prints valid token to console
const state = generateRandomString(16);
localStorage.setItem(Credentials.stateKey, state);
let url = 'https://accounts.spotify.com/authorize';
url += '?response_type=token';
url += '&client_id=' + encodeURIComponent(Credentials.client_id);
url += '&scope=' + encodeURIComponent(Credentials.scope);
url += '&redirect_uri=' + encodeURIComponent(Credentials.redirect_uri);
url += '&state=' + encodeURIComponent(state);
this.props.onConnectWithSpotify(access_token); // --> callback here
const {spotifyToken} = this.props
console.log('Spotify Token', spotifyToken); // --> this prints token undefined
window.location = url;
console.log(window.location )
};
不知何故,我无法在 Child 更新 this.state.spotifyToken。我在控制台得到“未定义”。
我错过了什么?
【问题讨论】:
-
您可能还需要将
spotifyToken作为道具传递给子组件。 -
console.log('Spotify Token', this.props.spotify_token); // --> this prints token undefined。您的Spotify component不包含名为spotify_token的道具 -
您通过调用
onConnectWithSpotify更改父级的状态,React 需要一些时间来重新渲染您的组件。因此,它不会立即在您的handleRedirect中更新,它仍然是旧的spotifyToken值,即 '' -
完全有道理。那么解决方案是什么?
-
如果你使用类添加
componentDidUpdate,如果你使用函数来观察变化,则添加'useEffect'。
标签: javascript reactjs