Ben*_*ime 3 javascript react-native redux
我有一个简单的react-native应用程序和一个redux存储设置.基本上我想添加一个新故事,发送redux动作并在创建后转换到这个新故事.
我的Container Component中有以下代码,当用户点击add按钮时会运行该代码.
addStory() {
this.props.actions.stories.createStory()
.then(() => Actions.editor({ storyId: last(this.props.stories).id }); // makes the transition)
}
Run Code Online (Sandbox Code Playgroud)
以及动作创作者.
export const createStory = () => (dispatch) => {
dispatch({ type: CREATE_STORY, payload: { storyId: uniqueId('new') } });
return Promise.resolve();
};
Run Code Online (Sandbox Code Playgroud)
如您所见,我在动作创建者中返回一个承诺.如果我不在此处返回承诺,则将在状态更新之前进行转换.
这对我来说有点奇怪 - 为什么我必须在这里返回一个已经解决的Promise?不是发送意味着同步吗?
如评论中所述
回调示例:
addStory() {
this.props.actions.stories.createStory( (id) => {
Actions.editor({ storyId: id })
});
}
export const createStory = ( callback ) => (dispatch) => {
const _unique_id = uniqueId('new');
dispatch({ type: CREATE_STORY, payload: { storyId: _unique_id } });
callback(_unique_id);
};
Run Code Online (Sandbox Code Playgroud)
超时示例: 这里我们假设状态现在已经更新了......大多数情况并非如此.
addStory() {
this.props.actions.stories.createStory()
setTimeout( () => {
Actions.editor({ storyId: last(this.props.stories).id });
}, 500);
}
export const createStory = () => (dispatch) => {
dispatch({ type: CREATE_STORY, payload: { storyId: uniqueId('new') } });
};
Run Code Online (Sandbox Code Playgroud)
承诺: 这可能需要一秒或一分钟才能完成..没关系.你做了你必须在这里做的一切,并最终解决它,以便应用程序/组件可以执行下一步操作.
export const createStory = () => (dispatch) => {
return new Promise( (resolve, reject) => {
// make an api call here to save data in server
// then, if it was successful do this
dispatch({ type: CREATE_STORY, payload: { storyId: uniqueId('new') } });
// then do something else
// do another thing
// lets do that thing as well
// and this takes around a minute, you could and should show a loading indicator while all this is going on
// and finally
if ( successful ) {
resolve(); // we're done so call resolve.
} else {
reject(); // failed.
}
});
};
Run Code Online (Sandbox Code Playgroud)
现在,结帐http://reactivex.io/rxjs/
| 归档时间: |
|
| 查看次数: |
4230 次 |
| 最近记录: |