【发布时间】:2016-05-11 18:09:17
【问题描述】:
我正在尝试使用 AJAX 调用更新带有数字的 div。这是小部件:
import {store} from './Store';
class Widget extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
let req = function() {
let xhr = new XMLHttpRequest();
xhr.open('GET', this.props.apiUrl, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.response) {
store.dispatch({
type: 'SET_STATE',
state: {
foo: JSON.parse(xhr.response)
}
});
}
}
}.bind(this);
xhr.send();
}
req.call(this);
}
render() {
return(
<widget>
<div>{this.props.foo}</div>
</widget>
);
}
}
这里是“减速器”:
import {List, Map} from 'immutable';
export default function(state = Map(), action) {
switch(action.type) {
case 'SET_STATE':
return state.merge(action.state);
}
return state;
}
这里是商店:
import {createStore} from 'redux';
import reducer from '../reducer';
export const store = createStore(reducer);
当我运行此代码时,我会加载要加载的页面,但 foo 未定义。该请求返回带有正确数据的响应。 dispatch() 被正确调用。如何异步触发在整个应用中传播的状态更改?
注意
拜托,拜托,拜托不要将我转发到像 this 或 this 这样的冗长抽象博客文章。我需要一个使用store.dispatch() 触发状态更改的代码的实际工作示例。谢谢。
【问题讨论】:
-
你没有使用
react-redux吗? -
一旦你的 reducer 运行,它应该触发并重新渲染,这取决于你连接组件的方式。
-
我猜这个组件不是
connected -
你缺少 react-redux 绑定 redux.js.org/docs/basics/UsageWithReact.html
-
@azium 我将
store作为组件导入。请看更新
标签: javascript reactjs redux react-redux