我正在尝试在我的react-native应用程序中使用redux。基本上,我在authActions.js文件中定义了一个signIn操作:
const signInAction = () => {
return {
type: 'signIn',
};
};
export { signInAction };
然后我在authReducer.js中定义了一个authReducer:
const initialState = {
isAuthenticated: false,
}
const authReducer = (state = initialState, action) => {
switch(action.type) {
case "signIn":
return Object.assign({}, state, {
isAuthenticated: true,
})
default: return state;
}
};
export default authReducer;
我将减速器合并到我的rootReducer.js文件中
import { combineReducers } from 'redux';
import auth from 'app/src/redux/reducers/authReducer.js';
const rootReducer = combineReducers({
auth,
});
export default rootReducer;
,然后在reduxIndex.js中创建商店:
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from 'app/src/redux/reducers/rootReducer.js';
let store = createStore(rootReducer, applyMiddleware(thunkMiddleware));
export default store;
我将我的应用程序包装在<Provider>
组件中,并且看起来工作正常(我可以从状态中读取并查看isAuthenticated的值。但是,当我尝试使用mapDispatchToProps调度一个动作时,在我看来功能未定义:
// More imports
// ...
import { connect } from 'react-redux';
import { signInAction } from 'app/src/redux/actions/authActions.js';
const mapStateToProps = (state) => {
return {};
}
const mapDispatchToProps = (dispatch) => {
return {
onSignIn: () => { dispatch(signInAction) },
};
}
class SignIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
}
}
onSignInPress() {
// ******* this is where the error occurrs ****
this.props.onSignIn();
}
render() {
const {navigation} = this.props;
return (
<View style={SignInStyles.container}>
<ScrollView>
<View>
<Button
large
title="SIGN IN"
backgroundColor={colors.primary}
onPress={this.onSignInPress}
/>
</View>
</ScrollView>
</View>
);
}
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
我真的看不到我要去哪里,但是我确定这是一个简单的错误。我得到的具体错误是:
“未定义不是对象。评估this.props.onSignIn”
答案 0 :(得分:2)
onSignInPress
回调未绑定到任何特定对象,因此在调用它时,this
是undefined
。
修复它的简单方法是使用箭头语法使其始终处于绑定状态。在您的课程定义中:
onSignInPress = () => {
this.props.onSignIn();
}
Google找到了我this Medium article from Miron Machnicki,它非常详细地解释了差异以及可能的替代语法。