为什么我的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
答案 0 :(得分:0)
componentWillReceiveProps只会在道具发生变化时以及这不是初始渲染时调用。
如果您收到与以前完全相同的道具,则不会调用componentWillReceiveProps。
我们通过更新状态中的新值来触发它。
所以在这里,您需要调度函数login
this.props.login(user, pass)
这不会调用你的reducer函数
调度的同义词就像this.props.dispatch(xyz.login(user, pass)}
那么它会调用reducer函数登录和更新状态