【问题标题】:Returning / Resolving object from action creator thunk - Is this okay?从动作创建者 thunk 返回/解析对象 - 这可以吗?
【发布时间】:2016-10-03 18:36:06
【问题描述】:

我对 react 和 redux 还很陌生,所以我不太确定以下是否被认为是一种好的做法。

我的情况是,我有一个使用 redux 作为状态容器的 react-native 项目。我有一个带有添加按钮的普通View。如果用户单击该按钮,则会调用一个动作创建者,它将向我的 Web 服务发出 GET 请求。 Web 服务返回一个预填充的对象,我需要将其传递给下一个导航器场景。使用redux - 在promise 解决后依赖action 可以吗?还是我必须把它从州里拉出来?

按钮按下事件:

addStory() {
  this.props.actions.createStory().then((action) => {
    Actions.editor({ title: action.story.title, action.story });
  });
}

动作创建者:

export function createStorySuccess(story) {
  return { type: CREATE_STORY_SUCCESS, story };
}

export function createStory() {
  return dispatch =>
    StoryApi.createStory().then((story) => {
      return dispatch(createStorySuccess(story));
    }).catch((error) => {
      throw error;
    });
}

【问题讨论】:

  • 你会从该州获得什么“它”?依靠行动来做​​什么可以吗?

标签: javascript reactjs react-native redux


【解决方案1】:

只要涵盖 Promise 的所有可能结果,您就可以依赖 Redux。我的意思是,除了抛出错误之外,您还需要调度失败操作,因此您的异步操作应如下所示:

export function createStorySuccess(story) {
  return { type: CREATE_STORY_SUCCESS, story };
}

export function createStoryFailure(errorMessage) {
  return { type: CREATE_STORY_FAILURE, failed: true, errorMessage };
}

export function createStory() {
  return dispatch =>
    StoryApi.createStory().then((story) => {
      return dispatch(createStorySuccess(story));
    }).catch((error) => {
      return dispatch(createStoryFailure('Loading the story failed.'));
    });
}

当获取故事时,您很可能还需要在此处添加获取操作。

之后你可以在你的组件中做这样的事情:

let renderResult;
if(this.props.failed) {
   renderResult = <div> {this.props.errorMessage} </div>;
} else {
   renderResult = <div> {this.props.story} </div>;
}

return (renderResult)

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 2017-02-10
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多