2017-08-31 95 views
4

爲什麼我的componentWillReceiveProps不能在我的react-native上運行,我使用react-navigation和redux。我執行按鈕登錄reducer我使用immutable。在商店已經更新,但componentWillReceiveProps沒有運行只是跳轉到componentWillUpdate和DidUpdate只有componentwillreceiveprops not called on react-native and redux

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) 

在減速,我已經用一成不變的,但爲什麼要在這個更新,仍然receiveProps上不叫組件

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

componentWillReceiveProps只會在道具發生變化時以及不是初始渲染時調用。

如果您接收到與以前完全相同的道具,則不會調用componentWillReceiveProps。

我們通過更新狀態中的新值來觸發它。

所以在這裏,你需要派遣功能login

this.props.login(user, pass)這不會打電話給你的減速功能

派遣SYNTEXT就像this.props.dispatch(xyz.login(user, pass)}那麼它將被稱爲減速功能的登錄和更新狀態