【问题标题】:ReactJS+Redux: How to handle a prop that depends on another propsReactJS+Redux:如何处理依赖于另一个 props 的 props
【发布时间】:2016-09-23 08:18:55
【问题描述】:

我正在创建一个Graph 一个React.Component。当componentWillMount 时,此图将负责使用异步操作加载配置文件。配置文件中还包含需要获取的查询信息。

现在,我将两个请求(配置 + 查询)链接起来,并将它们的结果存储在当前的 Redux 状态中。

{
    configurations: [{
        "my-configuration": 
        {
            // information about the configuration
            query: "my-query"
        }
    }],
    queries: [{
        "my-query" : {
            // information about the query
        }
    }]
}

我希望我的 Graph 组件对于两个变量都是 connected。但是,在获取配置之前,我不知道查询名称。

const mapStateToProps = (state, ownProps) => ({
    configuration: state.getIn([
        "configurations",
        ownProps.configurationName
    ]),
    query: state.getIn([
        "queries",
        queryName // the name of the query comes is known in the configuration
    ]),
});

我可能会遇到设计问题,但我希望得到您的反馈。这种情况你会怎么处理?

目前,我为组件创建了一个状态,但它需要与 redux 状态同步。

环境

  • react@15.3.1
  • redux@3.6.0
  • redux-thunk@2.1.0

【问题讨论】:

  • 是什么阻止您从配置中接收queryName 并使用它来获取道具查询?
  • @elmeister,你会怎么做?

标签: reactjs redux react-router web-component redux-router


【解决方案1】:

编辑:如果 myConfig 为 null 并等待从服务器获取怎么办?

选择器变成

const mapStateToProps = (state, ownProps) => {
  const myConfig = state.getIn([
    "configurations",
    ownProps.configurationName
  ]);
  return {
    configuration: myConfig,
    query: myConfig ? state.getIn([
        "queries",
        myConfig.queryName 
    ]) : *defaultQuery*,
  };
};

您应该处理在异步操作中获取myConfig

const getMyConfig = (...args) => (dispatch) => {
  dispatch(GET_MY_CONFIG_REQUEST);
  api.getMyConfig(...args)
    .then((res) => dispatch({ type: GET_MY_CONFIG_SUCCESS, res }))
    .catch((err) => dispatch({ type: GET_MY_CONFIG_FAIL, err }));
}

并且在 reducer 中需要在 GET_MY_CONFIG_SUCCESS 操作时更新 myConfig

...
case GET_MY_CONFIG_SUCCESS:
  return { ...state, myConfig: action.res };
...

原答案

这样的?

const mapStateToProps = (state, ownProps) => {
  const myConfig = state.getIn([
    "configurations",
    ownProps.configurationName
  ]);
  return {
    configuration: myConfig,
    query: state.getIn([
        "queries",
        myConfig.queryName 
    ]),
  };
};

【讨论】:

  • 类似这样,但 myConfig 可以为 null,因为它尚未从服务器获取。
【解决方案2】:

阅读这篇关于您should know about Redux 的好文章,您会发现以下内容:

在 mapStateToProps 中对数据进行非规范化是正常的。当我第一次开始使用 Redux 时,我不确定在 mapStateToProps 函数中进行“计算”是否符合规定。我在 Redux 存储库或文档中没有看到这样的示例。我花了几个星期才找到使用 mapStateToProps 中的“选择器”的其他人。你不知道我是多么兴奋发现有人这样做!

希望这可以帮助其他人!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2015-08-02
    • 2020-11-02
    • 1970-01-01
    • 2018-07-01
    • 2019-11-16
    • 1970-01-01
    相关资源
    最近更新 更多