由于某些原因,当我第一次加载页面时,reducer函数和状态可以正确执行,但是您可以访问数据。一旦切换到另一页,然后返回到上一页,它说状态未定义。这是图片
以下文件中的代码如下:
import React, { Component } from "react";
import Hook from "../../hooks/display";
import { connect } from "react-redux";
import * as actionTypes from "../../store/actions";
import "./main.css";
class Main extends Component {
componentDidMount() {
console.log(this.props.stateName);
this.props.console_inside();
console.log("hey");
}
render() {
return (
<div>
<h1>The container view (page)</h1>
<Hook />
</div>
);
}
}
const mapStateToProps = state => {
return {
stateName: state.inside_reducer
};
};
const mapDispatchToProps = dispatch => {
return {
console_inside: () => dispatch({ type: actionTypes.DO_SOMETHING_1 })
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Main);
和我的reducer.js
import * as actionTypes from "./actions";
const initialState = {
persons: [],
inside_reducer: "I am inside of a reducer"
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.DO_SOMETHING_1:
console.log(state.inside_reducer);
return 1;
case actionTypes.DO_SOMETHING_2:
return 1;
}
return state;
};
export default reducer;
问题应该是
1)为什么第二次进入页面时它显示未定义?
P.S:不确定是否重要,以防万一问题出在这里 在我的index.js中
import * as serviceWorker from "./serviceWorker";
import { BrowserRouter } from "react-router-dom";
import { createStore } from "redux";
import { Provider } from "react-redux";
import reducer from "./store/reducer";
const store = createStore(reducer);
const app = (
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
ReactDOM.render(app, document.getElementById("root"));
答案 0 :(得分:3)
您永远不会返回自己的状态
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.DO_SOMETHING_1:
console.log(state.inside_reducer);
return state ; // <==== You must return your state instead of 1
case actionTypes.DO_SOMETHING_2:
return state ; // <==== You must return your state instead of 1
}
return state;
};
答案 1 :(得分:1)
我非常确定这是因为您将状态设置为1,而不是返回任何想要的新状态!
1.inside_reducer确实是不确定的。
Reducer返回新状态,因此您要重写它。我不确定您要达到的目标,但可以尝试以下方法
return {
...state,
inside_reducer: 'reduced'
}
在两种情况下都是如此。