我必须不正确地进行此设置,因为它无法正常工作。如果将console.log放在我的if语句中,那么它将显示出来,所以我知道它已经到了这一点,但它没有重定向。我做错了吗...
...
checkUserAuth = () => {
return fetch(process.env.REACT_APP_API_URL + '/authCheck', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': window.localStorage.getItem('token')
},
body: JSON.stringify({
itemid: this.props.itemid
})
})
}
render(){
this.checkUserAuth().then(response => response.json()).then(data => {
if(data === 'false') {
return <Redirect to='/' />
}
}).catch(err => console.log(err))
....
答案 0 :(得分:1)
对于副作用用例,请使用componentDidMount()
,然后更新将触发render
方法的内部状态:
checkUserAuth = () => {
return fetch(process.env.REACT_APP_API_URL + '/authCheck', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': window.localStorage.getItem('token')
},
body: JSON.stringify({
itemid: this.props.itemid
})
})
}
componentDidMount() {
this.checkUserAuth().then(response => response.json()).then(data => {
this.setState({data});
});
}
render() {
if(data === 'false') {
return <Redirect to='/' />
} else {
... do something else
}
}