reactjs - React-Redux mapStateToProps 不更新组件
问题描述
所以我简化了我的代码,但基本上我有一个直截了当的 redux 商店:
/* store.js */
import { createStore } from 'redux';
const reducer = (state = {}, action) => {
if (action.type === 'action') state.data = data;
return state;
}
const store = createStore(reducer);
store.subscribe(() => {
console.log(store.getState()); // returns the right state, updates properly
});
export default store;
从服务器拉取数据并将其分派到存储的加载器:
/* Loader.js */
class Loader {
dispatch (allDocuments) {
store.dispatch({
type: 'action',
data: data
});
}
async fetchData () {
try {
const allDocuments = await ajaxCall('GET', '/fetchData');
this.dispatch(allDocuments);
return allDocuments;
} catch (e) {
console.error(e);
}
}
}
export default Loader;
然后这是我的 App.js 文件,我每 5 秒触发一次 Loader fetch 方法,并将存储状态映射到 React 组件:
/* App.js */
import Loader from './Loader';
const loader = new Loader();
setInterval(async () => {
await loader.fetchData();
}, 5000);
const App = ({
data
}) => {
console.log(data); //doesn't update
return (
<div>
<p>{data}</p>
</div>
)
};
const mapStateToProps = state => ({data: state.data,})
export default connect(mapStateToProps)(App);
所以这里的问题是组件没有更新。Loader 正确调度,redux store 确实得到了更新,但 App 中的 data 属性仍然是一个空对象,并且不会重新触发 render 方法。
为什么 mapStateToProps 在 store 状态发生变化时不更新组件?
解决方案
您的减速器不会保存action.data
有效负载。它也没有返回新的状态对象引用。
const reducer = (state = {}, action) => {
if (action.type === 'action') state.data = data; // <-- mutation
return state;
}
当动作类型匹配时,您应该返回一个带有action.data
有效负载的新状态对象引用。
const reducer = (state = {}, action) => {
if (action.type === 'action') {
return {
...state,
data: action.data;
};
}
return state;
}
推荐阅读
- mongodb - MongoDB - 如何过滤包含键的文档
- wordpress - 在使用木材的第一页之后每页使用不同的帖子?
- graphql - 如何指定采用多种类型的 graphql 类型?
- c# - 编写实用程序类时异常处理的最佳实践 c#
- python - Keras Convolution1D 输入形状
- android - 如何从activivty调用服务中的进度对话框
- javascript - 当用户开始输入时如何显示输入的最大长度?
- java - 在这里,Main 类抛出 DERIVED 而不将 Main 声明为 THROWS 但它有效,谁能解释一下
- python-3.x - Downloading files using Python requests
- jquery - 无法使用 Chrome 加载 @font-face,jquery 出错?