简体   繁体   English

如何在异步 HTTP 请求中使用 react-redux 存储

[英]How to use react-redux store with Async HTTP Request

I'm trying to update a div with a number using an AJAX call.我正在尝试使用 AJAX 调用更新带有数字的 div。 Here's the widget:这是小部件:

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>
        );
    }
}

Heres the "reducer":这是“减速器”:

import {List, Map} from 'immutable';
export default function(state = Map(), action) {
    switch(action.type) {
        case 'SET_STATE':
            return state.merge(action.state);
    }
    return state;
}

And here's the store:这是商店:

import {createStore} from 'redux';
import reducer from '../reducer';

export const store = createStore(reducer);

When I run this code, I get the page to load, but foo is undefined.当我运行此代码时,我加载了页面,但foo未定义。 The request returns a response with the correct data.该请求返回一个带有正确数据的响应。 dispatch() is being called correctly. dispatch()被正确调用。 How do I trigger a state change asynchronously that propagates throughout the entire app?如何异步触发在整个应用程序中传播的状态更改?

NOTE笔记

Please, please, please do not forward me to verbose abstract blog posts like this or this .拜托,拜托,请不要将我转发到像这样这样的冗长抽象的博客文章。 I need an actual working example of code that triggers a state change using store.dispatch() .我需要一个使用store.dispatch()触发状态更改的代码的实际工作示例。 Thanks.谢谢。

As Azium mentioned in the comments, you don't need redux-thunk to do this, however this is how you would.正如 Azium 在评论中提到的那样,您不需要 redux-thunk 来执行此操作,但是您可以这样做。

You apply redux-thunk middleware to your store:您将 redux-thunk 中间件应用到您的商店:

var thunk = require('redux-thunk');
const store = createStore(
    combineReducers({
        reducer1,
        reducer2
    }),
    applyMiddleware(thunk)
);

Then you can define actions like this:然后你可以定义这样的动作:

export const getData = () => {
    return (dispatch) => {
        return fetch('/foo')
            .then((response) => response.json())
            .then((json) => dispatch(receieveData(json)));
    };
};

Where receieveData is another action that you have defined.其中,receieveData 是您定义的另一个操作。

Now you could call this action in componentWillMount .现在您可以在componentWillMount调用此操作。 I might have missed something, but that's the gist of it.我可能错过了一些东西,但这就是它的要点。 It's all in the first link from your original post ( http://redux.js.org/docs/advanced/AsyncActions.html ).这一切都在您原始帖子 ( http://redux.js.org/docs/advanced/AsyncActions.html ) 的第一个链接中。

Edit: and of course, as many have said already, you need react-redux :)编辑:当然,正如许多人已经说过的,您需要 react-redux :)

I found out what was wrong.我发现出了什么问题。 I was not setting the initial state.我没有设置初始状态。

// 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
    })
})

Without this, the state being updated was always null .没有这个,被更新的状态总是null This simple fact was not in any of the official React/Redux documents.这个简单的事实并没有出现在任何官方的 React/Redux 文档中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM