【发布时间】:2019-05-27 08:27:22
【问题描述】:
我能够读取 redux store(Props) 的值,但我无法更新 redux 状态值(Props2),当动作似乎被分派到 reducer 函数时。
页面:
componentDidMount(){
console.log("Props:"+this.props.user)
}
dummyFunction() {
//Redux
this.props.toggleTheme('red');
//which prints the object above in the screenshot
console.log(this.props.toggleTheme('red'));
console.log("Props2:"+this.props.user);
}
const mapStateToProps = state => ({
user: state.user.userData,
});
const mapDispatchToProps = dispatch => ({
toggleTheme: (user) => dispatch(toggleTheme(user)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Tab1Screen);
减速机:
const initialState = {
userData: "Apple",
};
const user = (state = initialState, action) => {
switch (action.type) {
case 'TOGGLE_THEME':
switch(action.payload) {
case 'red':
console.log("Payload1:"+ action.payload);
return { userData: "Orange" };
case 'blue':
console.log("Payload2:"+ action.payload);
return { userData: "Pear" };
}
default:
console.log("Payload:3"+ action.payload);
return state;
}
};
export default user;
动作:
import { TOGGLE_THEME } from './actionTypes';
//which TOGGLE_THEME = 'TOGGLE_THEME'
export const toggleTheme = user => ({
type: TOGGLE_THEME,
payload: user,
});
包.json
"dependencies": {
"@expo/samples": "2.1.1",
"expo": "^32.0.0",
"react": "^16.8.6",
"react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
"react-navigation": "^3.0.9",
"react-redux": "^6.0.1",
"redux": "^4.0.1",
}
更新:当我导航到另一个页面并且它正常工作时,尝试检索状态,检索橙色值。我如何能够在同一页面中获得正确的值(在 dummyFunction 中)?
【问题讨论】:
-
我想说不是在你的 reducer 中返回一个新的 state obj,你可以像
return {...state, userData: "Orange"}那样修改它,为了调试目的,尝试简化你的 switch 语句,看看出了什么问题 -
嗨@AmrAly,我试过......状态无济于事。奇怪的是,一旦您导航到另一个页面,就会检索更新的值,这意味着 switch 语句工作正常。
-
在this 的回答中,这个家伙说你不能只用控制台登录相同的功能,而是可以在
componentWillReceiveProps中进行操作 -
即使我第二次调用该函数,它仍然显示“红色”。我猜它更倾向于“mapStateToProps”而不是刷新。
-
你可以像这样控制台日志:
const mapStateToProps = state => ( console.log('state:',state); return { user: state.user.userData, });
标签: react-native redux expo