Javascript 如何将react redux存储与异步HTTP请求一起使用
我正在尝试使用AJAX调用用数字更新div。以下是小部件:Javascript 如何将react redux存储与异步HTTP请求一起使用,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,我正在尝试使用AJAX调用用数字更新div。以下是小部件: import {store} from './Store'; class Widget extends React.Component { constructor(props) { super(props); } componentWillMount() { let req = function() { let xhr = new XMLHttpReque
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 {createStore} from 'redux';
import reducer from '../reducer';
export const store = createStore(reducer);
当我运行这段代码时,我得到了要加载的页面,但是foo
是未定义的。请求返回具有正确数据的响应<代码>调度()正在正确调用。如何异步触发在整个应用程序中传播的状态更改
注意
请,请,请不要把我转发给像或这样冗长的抽象博客文章。我需要一个使用
store.dispatch()
触发状态更改的实际工作代码示例。谢谢。正如Azium在评论中提到的那样,您不需要redux thunk来完成这项工作,但这是您应该做的
您将redux thunk中间件应用于您的商店:
var thunk = require('redux-thunk');
const store = createStore(
combineReducers({
reducer1,
reducer2
}),
applyMiddleware(thunk)
);
然后可以定义如下操作:
export const getData = () => {
return (dispatch) => {
return fetch('/foo')
.then((response) => response.json())
.then((json) => dispatch(receieveData(json)));
};
};
其中ReceiveData是您定义的另一个操作
现在您可以在组件willmount
中调用此操作。我可能错过了什么,但这就是要点。这一切都在您原始帖子()的第一个链接中
编辑:当然,正如许多人已经说过的,你需要react redux:)我发现了问题所在。我没有设置初始状态
// Store.jsx
import {fromJS} from 'immutable';
import {createStore} from 'redux';
import reducer from '../reducer';
export const store = createStore(reducer);
store.dispatch({
type:'SET_STATE',
state: fromJS({
foo: 0
})
})
如果没有此选项,更新的状态总是
null
。这一简单事实不在任何官方React/Redux文档中。您是否未使用React Redux
?一旦减速器运行,它将触发并重新渲染,取决于您连接组件的方式。我猜此组件不是connect
ed您缺少react redux bindings@azium我正在导入store
作为组件。请查看更新
// Store.jsx
import {fromJS} from 'immutable';
import {createStore} from 'redux';
import reducer from '../reducer';
export const store = createStore(reducer);
store.dispatch({
type:'SET_STATE',
state: fromJS({
foo: 0
})
})