我明白以前曾多次问过这样的问题,但我已经用尽了所有的资源和选择,也弄不清楚为什么不起作用。当我创建动作"AUTHENTICATION_LOGOUT"时,我可以跟踪它到动作还原器,并可以看到从动作还原器返回新的状态,但是connect不会在组件中获取它,因此mapStateToProps不会运行。我为state返回一个新对象,所以检查应该将其标记为状态更改,而不是状态突变,对吗?是错误还是版本错配?谢谢。
在auth_actions中:
export const appLogout = () => async dispatch => {
await AsyncStorage.removeItem(USER);
dispatch({ type: "AUTHENTICATION_LOGOUT" });
};在auth_reducer.js中
export default function (state = {}, action) {
switch (action.type) {
case "AUTHENTICATION_SUCCESS":
return { user: action.payload };
case "AUTHENTICATION_LOGOUT":
return {user: null };
default:
return state;
}
}在index.js中的还原器文件夹中:
export default combineReducers({
search, auth
});在AuthComponent.js中:
import React, { Component } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { connect } from 'react-redux';
class AuthScreen extends Component {
...
}
function mapStateToProps(state) {
let { auth } = state;
return { user: auth.user };
}
export default connect(mapStateToProps, actions)(AuthScreen);而这家商店:
const store = createStore(
reducers,
{},
compose(
applyMiddleware(thunk)
)
);
export default store;在App.js中
import store from './store';
import { Provider } from 'react-redux';
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<MainNavigation />
</Provider>
);
}
}package.json:
"dependencies": {
"axios": "^0.18.0",
"expo": "^27.0.0",
"react": "16.3.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-27.0.0.tar.gz",
"react-redux": "^5.0.7",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0"
}更新了,在深入挖掘之后,我发现了问题所在。这里的问题,当然,我没有看到,是这个组件被卸载了,因此根本没有收到任何状态更新。我用componentWillUnmount生命周期挂钩检查了它。它与状态突变没有任何关系。我被所有关于国家变异的谈话和帖子吓得半途而废。感谢大家宝贵的帮助和时间。
发布于 2018-05-31 20:08:26
永远不要使用function本机,所以我可能遗漏了一个东西,但是我相信redux希望分派参数中的操作是一个返回实际动作对象的函数。另外,函数应该从另一个文件中导入。
检查AUTHENTICATION_LOGOUT值是一个字符串
以这种方式使用es6您的mapStateToProps会更好:
({auth: {user}) => ({user})发布于 2018-05-31 21:12:09
您可能忘记使用Provider了。
另一个技巧是,您可以这样改进您的mapStateToProps函数:
const mapStateToProps = ({auth}) => auth;或者如果你在使用兰达:
const mapStateToProps = prop('auth');您不需要在mapStateToProps函数中创建一个新对象,因为还原器已经在这样做了。注意,auth是一个只有一个属性:user的对象,所以您可以从状态中获取auth,仅此而已(垃圾收集器的工作稍微少了一点:-)。
https://stackoverflow.com/questions/50631791
复制相似问题