Javascript 用getDerivedStateFromProps替换组件将在redux中接收Props,但不发射
我在使用redux时遇到问题。我想替换Javascript 用getDerivedStateFromProps替换组件将在redux中接收Props,但不发射,javascript,reactjs,redux,Javascript,Reactjs,Redux,我在使用redux时遇到问题。我想替换组件将接收道具升级到react 16,但不知何故它不会启动。下面是我的容器组件代码 @connect(state=>({user: state.user, global: state.global}), {loginUser}) class LoginFormContainer extends React.Component { constructor() { super() this.state = { email:
组件将接收道具升级到react 16,但不知何故它不会启动。下面是我的容器组件代码
@connect(state=>({user: state.user, global: state.global}), {loginUser})
class LoginFormContainer extends React.Component {
constructor() {
super()
this.state = {
email: '',
password: '',
isAuthenticated: false
}
}
//but this worked?
componentWillReceiveProps(nextProps) {
if(nextProps.user.isAuthenticated !== this.props.user.isAuthenticated && nextProps.user.isAuthenticated) {
this.props.history.location.replace('/dashboard')
}
}
/*static getDerivedStateFromProps(nextProps, prevState) {
console.log('not even fired?')
if (nextProps.user.isAuthenticated !== prevState.isAuthenticated) {
return {
isAuthenticated: '/dashboard'
}
}
return null
}*/
handleSubmit() {
const { email, password } = this.state
this.props.loginUser(email, password)
}
render(){
this.state.isAuthenticated && <Redirect to={'/dashboard'} />
return(
<LoginForm />
)
}
}
export default LoginFormContainer
@connect(state=>({user:state.user,global:state.global}),{logiuser})
类LoginFormContainer扩展了React.Component{
构造函数(){
超级()
此.state={
电子邮件:“”,
密码:“”,
I验证:错误
}
}
//但这奏效了吗?
组件将接收道具(下一步){
if(nextrops.user.isAuthenticated!==this.props.user.isAuthenticated&&nextrops.user.isAuthenticated){
this.props.history.location.replace(“/dashboard”)
}
}
/*静态getDerivedStateFromProps(下一步,上一步){
console.log('甚至没有被激发?')
if(nextrops.user.isAuthenticated!==prevState.isAuthenticated){
返回{
isAuthenticated:“/dashboard”
}
}
返回空
}*/
handleSubmit(){
const{email,password}=this.state
this.props.logiuser(电子邮件、密码)
}
render(){
this.state.isAuthenticated&&
返回(
)
}
}
导出默认LoginFormContainer
此.state.isAuthenticated
是一个表示身份验证状态的布尔值,在getDerivedStateFromProps
中将其设置为'/dashboard'
不会更改路由。您仍然需要调用this.props.history.replace('/dashboard')
对于路线更改操作,您应该将组件WillReceiveProps更改为组件DidUpdate。请注意,您应该使用this.props
引用更新的道具,并使用componentdiddupdate
的第一个参数引用以前的道具
成功登录后,最好在logiuser
中执行路由重定向,如果isAuthenticated
缓存在本地,则componentDidMount
执行路由重定向。您的React版本是什么,getDerivedStateFromProps不在版本16中,但在版本16.3.0中,我还想指出,您不需要立即交换您的组件。要升级到16.3.0,您仍然可以升级,而无需切换