我是redux的新手,对两者都有反应。我正在尝试我的第一个redux应用,其中我的状态以未定义状态通过。尽管我在互联网上搜索以找出问题所在,但无法找出问题所在。
下面是代码段-
Init.js
export default function() {
return {
isLoggedIn: false,
username: "admin"
};
}
Reducer.js
import initialState from "./init";
let currentState = initialState;
export default function(state = currentState, action) {
if (action.type === "ONLICK") {
return state;
} else {
return state;
}
}
Index.js
const allReducers = combineReducers({
currentstate: currentState
});
export default allReducers;
currentState.js
import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { allreducers } from "./../reducer/index";
class CurrentState extends Component {
render() {
console.log("Logged In-" + this.props.isLoggedIn);
return <div>{this.props.isLoggedIn}</div>;
}
}
function mapStateToProps(state) {
return {
isLoggedIn: state.isLoggedIn
};
}
export default connect(mapStateToProps)(CurrentState);
navbar.js
import React, { Component } from "react";
import CurrentState from "./../container/currentstate";
import "bootstrap/dist/css/bootstrap.css";
class Navbar extends Component {
constructor() {
super();
}
render() {
return (
<div>
<h3>State -</h3>
<CurrentState />
</div>
);
}
}
Navbar.js是显示状态属性之一的地方。但是在控制台中,当我尝试打印该值时,它将显示为未定义。
答案 0 :(得分:0)
您在 mapStateToProps
中以错误的方式获取状态使用
function mapStateToProps(state) {
return {
isLoggedIn: state.currentstate
};
}
代替
function mapStateToProps(state) {
return {
isLoggedIn: state.isLoggedIn
};
}
希望如此会有所帮助