延迟加载来自规范化Redux存储的引用

时间:2016-03-29 19:15:19

标签: asynchronous reactjs redux

哟!我正在使用Redux和Normalizr。我正在使用的API会发送如下所示的对象:

{
  name: 'Foo',
  type: 'ABCD-EFGH-IJKL-MNOP'
}

或者像这样

{
  name: 'Foo2',
  children: [
    'ABCD-EFGH-IJKL-MNOP',
    'QRST-UVWX-YZAB-CDEF'
  ]
}

我希望能够在从状态(type)访问上述对象时异步获取这些相关实体(childrenmapStateToProps)。不幸的是,这似乎与Redux方式不相符,因为mapStateToProps不适合调用操作。我忽略了这个案例的明显解决方案(除了预取我的所有数据)吗?

1 个答案:

答案 0 :(得分:2)

不确定我是否正确理解了您的用例,但如果您想获取数据,一种简单的常见方法是从React组件触发它:

var Component = React.createClass({
    componentDidMount: function() {
        if (!this.props.myObject) {
            dispatch(actions.loadObject(this.props.myObjectId));
        }
    },

    render: function() {
        const heading = this.props.myObject ?
            'My object name is ' + this.props.myObject.name
            : 'No object loaded';
        return (
            <div>
                {heading}
            </div>
        );
    },
});

鉴于&#34; myObjectId&#34; prop,组件触发&#34; myObject&#34;安装后取出。

另一种常见的方法是从Redux异步操作创建器获取数据(如果它尚未存在)(有关此模式的更多详细信息,请参阅Redux's doc):

// sync action creator:
const FETCH_OBJECT_SUCCESS = 'FETCH_OBJECT_SUCCESS';
function fetchObjectSuccess(objectId, myObject) {
    return {
        type: FETCH_OBJECT_SUCCESS,
        objectId,
        myObject,
    };
}

// async action creator:
function fetchObject(objectId) {
    return (dispatch, getState) => {
        const currentAppState = getState();
        if (!currentAppState.allObjects[objectId]) {
            // fetches the object if not already present in app state:
            return fetch('some_url_.../' + objectId)
                .then(myObject => (
                    dispatch(fetchObjectSuccess(objectId, myObject))
                ));
        } else {
            return Promise.resolve();  // nothing to wait for
        }
    };
}