reactjs – componentwillreceiveprops没有调用react-native和redux

为什么我的componentWillReceiveProps没有在我的react-native上运行,我使用react-navigation和redux.我使用immutable在reducer中执行按钮登录.在商店已更新但componentWillReceiveProps没有运行只跳转到componentWillUpdate和DidUpdate只

import React,{ Component } from 'react'

class Main extends Component{
  constructor(props){
    super(props)
    this.state = {
     active : '',username: '',password: ''
  }
}

componentWillReceiveProps(newProps) {
 console.log(newProps.load(),'Component WILL RECIEVE PROPS!')
}

componentWillUpdate(nextProps,nextState) {
 console.log(nextProps,nextState,'Component WILL UPDATE!');
}

componentDidUpdate(prevProps,prevState) {
 console.log(prevProps,'Component DID UPDATE!')
}

handleButtonAction(actions){
 let user = this.state.username
 let pass = this.state.password
 if(actions === 'login'){
   this.props.login(user,pass)
 }
}

render(){
  const {navigation} = this.props;
return(
          <Button block onPress={()=>this.handleButtonAction('login')} style=
   {{marginLeft: 10,marginRight: 10}}>
            <Text>Login</Text>
          </Button>
   )}

const mapStateToProps = state =>({
  token: state.token
})

const mapDispatchToProps = dispatch => ({
 login: (user,pass)=> dispatch({type:"LOGIN",payload:'testing'}),})

export default connect(mapStateToProps,mapDispatchToProps)(Main)

在Reducer中我已经使用了不可变但是为什么在这个更新中仍然在未调用的组件上接收

const listProduct = (oldstate,value)=>{
 console.log(oldstate);
 let newState = {...oldstate,data: value.data.data}
 console.log(newState);
 return newState
}

const login = (oldstate,value)=>{
 let newState = {...oldstate,token: value}
 return newState
}

const initialState = {}

const product = (state=initialState,actions)=>{
 switch (actions.type) {
 case "GET_PRODUCK": return listProduct(state,actions.payload);
 case "LOGIN": return login(state,actions.payload);
 default: return state
}}

export default product

解决方法

componentWillReceiveProps仅在道具发生变化时才会调用,而且这不是初始渲染时.

如果您收到与以前完全相同的道具,则不会调用componentWillReceiveProps.

我们通过更新状态中的新值来触发它.

所以在这里,你需要调度函数登录

this.props.login(user,pass)这不会调用你的reducer函数

调度的Syntext就像this.props.dispatch(xyz.login(user,pass)}那么它将调用reducer函数登录和更新状态

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...