![](/img/trans.png)
[英]Inferring mapped props when using TypeScript and React-Redux
[英]State not mapped to props react-redux
我有一个简单的LoginForm,我尝试映射redux的状态以做出反应。 这是我的LoginForm.js代码:
export class LoginForm extends React.Component {
render() {
console.log("**** FORM print store");
console.log(store.getState());
console.log("**** FORM print props");
console.log(this.props);
if(this.props.loginObj.loginState=='true') { // error here
console.log('yes');
}
return (
<div><div/>);
);
}
}
const mapStateToProps = (state) => ({
loginObj : state.loginObj
});
const mapDispatchToProps = (dispatch) => ({
doLogin,
changeText,
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(LoginForm);
reducer包含属性loginObj,如果我打印商店,则会看到:
loginObj:
Object { loginState="false", user="", password=""}
减速器:
const reducers = combineReducers({
loginObj: loginReducer
});
...
但是,当我尝试访问道具时,似乎this.props为空。
this.props.loginObj.loginState-this.props为null
更新:LoginForm:
import {bindActionCreators} from 'redux'; //must include
function mapStateToProps(state){
return {
loginObj : state.loginObj
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({doLogin,changeText},dispatch)
};
首先,请更正mapStateToProps
方法。 它没有返回值。 从该方法的语法可以清楚地看到。
其次,为什么要使用this.props.loginObj.loginState
? 此抽象级别是错误的。 正如您提到的loginObj
作为道具一样,那为什么还要在其中抽象loginState
属性呢? 它不会工作。
在redux中,您应该将道具限制为状态中的同一对象。 例如,如果您想从州做待办事项,则将待办事项作为道具。 如果您想要待办事项的某些属性,则将其传递给道具(对于此代码)或通过子道具。
我不知道您的商店,但是组件应该看起来像:
export class LoginForm extends React.Component {
render() {
console.log("**** FORM print store");
console.log(store.getState());
console.log("**** FORM print props");
console.log(this.props);
if (this.props.loginObj.loginState == 'true') { // error here
console.log('yes');
}
// for this issue you could view at this point -
// store.getState().loginObj.propertyyouwant only if you have
// imported main store in this current file
return (
<div>
</div>
);
}
}
const mapStateToProps = (state) => {
return { loginObj: state.loginObj}
};
const mapDispatchToProps = (dispatch) =>
{
return {
doLogin,
changeText,}
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(LoginForm);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.