因此,我在AppRouter.js
中管理用户身份验证,这是我的最高组件。
下面是它的工作原理:
componentDidMount() {
this.getUser()
}
getUser(history = undefined) {
const { cookies } = this.props
let jwt = cookies.get(this.state.cookieName)
if (!jwt) return null
AuthApi.getCurrentUser(jwt).then(response => {
if (response !== undefined) {
this.setState({
email: response.email,
userId: response.id,
firstName: response.first_name,
lastName: response.last_name,
phoneNumber: response.phone_number,
randomString: response.random_string,
jwt: jwt
})
if (history) history.push('/')
}
else {
// user has cookie but cannot load current user
cookies.remove(this.state.cookieName)
this.setState({
email: undefined,
firstName: undefined,
lastName: undefined,
phoneNumber: undefined,
randomString: undefined,
jwt: undefined,
userId: undefined
})
}
})
}
我的问题是,我还在子组件中调用了
componentDidMount()
,那里的代码取决于我的AppRouter
的componentDidMount()
输出结果。这是我的
MyOrdersPage.js
组件接收AppRouter
状态作为道具的示例:componentDidMount() {
axios.get('/api/v1/orders/' + this.props.currentUser.userId)
.then(response => {
console.log(response)
this.setState({
orders: response.data
})
})
.catch(error => console.log(error))
}
但是,
AppRouter
的componentDidMount()
在MyOrdersPage.js
的componentDidMount()
之后完成加载。因此,当this.props.currentUser.userId
的undefined
运行时,MyOrdersPage.js
是componentDidMount()
。如何更改代码,以使子组件中的
componentDidMount()
仅在componentDidMount()
中的AppRouter.js
加载完成后才加载? 最佳答案
正如@skyboyer在评论中提到的,我向父组件添加了状态isReady
,默认情况下设置为false
。 API调用加载完成后,它将变为true
:
AuthApi.getCurrentUser(jwt).then(response => {
if (response !== undefined) {
// do something
}
else {
// do someting else
}
}).then(() => this.setState({isReady: true}));
并在
render()
方法中:{this.state.isReady &&
<div>...</div>}
此外,实现react-loads也是一个好主意。