【发布时间】:2018-11-05 01:24:05
【问题描述】:
我有一个 react 组件,它在 componentWillMount 中进行 AJAX 调用,并支持接收到的数据以响应 redux 存储。这是代码
componentWillMount() {
var self = this;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
var json = JSON.parse(this.responseText);
var data = {
json
};
self.props.dispatch({
type: "ADD_Exams",
data
});
}
};
xmlhttp.open("GET", "http://127.0.0.1:8000/getExams/", true);
xmlhttp.send();
}
在reducer中,我将接收到的数据分配给reducer状态中定义的数组。
const initialState = {
exams:[]
}
const examreducer = (state = initialState, action) => {
switch (action.type) {
case "ADD_Exams":
return {
...state,
exams: [...state.exams, action.data.json]
};
default:
return state;
}
};
但是当我使用 mapStateToProps 读取考试变量时,我得到了未定义。
const mapStateToProps = (state) => {
return {
exams: state.exams
}
}
export default connect(mapStateToProps)(Exam);
我正在创建这样的商店
import { Provider } from "react-redux";
const store = createStore(loginReducer, examReducer);
ReactDOM.render(
<Provider store={store}>
<Exam />
</Provider>,
document.getElementById("root")
);
registerServiceWorker();
console.log(this.props.exams) 打印未定义。这里有什么问题?
【问题讨论】:
-
代码中的 console.log 在哪里?
-
在控制台上打印“/static/media/examReducer.d41d8cd9.bin”。
-
如何初始化存储?
-
它在组件的渲染函数中
-
通过像这样调用 createStore const store = createStore(loginReducer,examReducer);
标签: javascript reactjs redux