我目前已经建立了一个功能登录页面。登录后,我正在使用componentDidmount()获取数据以解析用户信息(名称等)
登录时,我当前正在使用react-router的Redirect;但是,这不会刷新页面。
登录后不使用重定向并重新加载页面的最佳方法是什么?这样我的信息可以从componentDidMount()获取。
我还使用了ComponentWillReceieveProps,但它也无法满足我对代码的需求
谢谢!
尝试:
From Login.js
const { error, loading, token } = this.props;
const { username, password } = this.state;
if (token) {
return <Redirect to="/home" />
}
from ArticleView.js:
axios.get('...') {
...
}
from Forms2.js:
componentWillReceiveProps(newProps){
console.log(newProps)
if (newProps.token !== this.props.token) {
authAxios.get("user")
.then(res =>{
this.setState({id: res.data.id});
this.setState({username:res.data.username});
});
}
console.log(newProps.token)
};
答案 0 :(得分:0)
为什么要改变整个组件流程而不是采用正确的生命周期方法?
如果ComponentWillReceieveProps()
尚未被弃用,很快就会被弃用,因为它给React团队带来了太多麻烦。它已替换为静态方法-getDerivedStateFromProps()
。
此方法与ComponentWillReceieveProps()
之间的最小区别是,作为静态方法,您将无法使用this
。
详细了解here。
我尝试将您的组件转换为使用getDerivedStateFromProps()
。但是由于this
,prevProps
和async/await
不能使用,因此出现了太多的复杂情况。
更简单的解决方案是使用React Hooks
const Login = ({ error, loading, token }) => {
const [username, setUsername] = React.useState();
const [id, setId] = React.useState();
const [password, setPassword] = React.useState();
React.useEffect(() => {
authAxios.get("user")
.then(res =>{
setId(res.data.id);
setUsername(res.data.username);
});
}, [token])
// UseEffect hooks will run if React detects
// changes in props.token
}
希望这会有所帮助