【问题标题】:Redux Selector not called未调用 Redux 选择器
【发布时间】:2020-03-04 21:29:01
【问题描述】:

我有以下情况:

我的应用状态中国家/地区列表的选择器

export const getCountries = state => state.countries;

还有一个使用 reselect 创建的选择器来过滤具有特定 id 的国家/地区

export const getCountryById = countryId => 
    createSelector(
        [getCountries],
        (countries) => {
            let countriesList = countries.filter(c => c.id === countryId);
            if ( countriesList ) {
                return countriesList[0];
            }
            return null;
        }
    )

然后有一个国家详情页面组件(通过http://localhost:3000/country/4 访问)

import React from 'react';
import { getCountryById } from '../redux/selectors';
import { connect } from 'react-redux';

const CountryPage = ({country}) => {
    return <h1>{country.name}</h1>
}

const mapStateToProps = (state, ownProps) => {
    console.log(ownProps.match.params.countryId);
    const obj = {
        country: getCountryById(ownProps.match.params.countryId)
    }
    return obj;
};

export default connect(mapStateToProps, null)(CountryPage);

mapStateToProps 正确接收 countryId,但未调用选择器。我在这里想念什么?

或者它是使用选择器的错误方法?我知道我可以在 CountryPage 中使用州的完整国家/地区列表并在那里进行过滤,但是这里的最佳做法是什么?

【问题讨论】:

    标签: reactjs redux reselect


    【解决方案1】:

    那是因为您的 getCountryById 实际上并不是一个选择器。这是一个返回选择器的函数。

    鉴于您尝试为每个组件使用唯一 ID 并进行过滤,您可能需要使用 the "factory function" form of mapState to create a unique selector instance per component instance 来获得正确的记忆行为。

    不过,话虽如此,您的选择器也可以简化。你在这里不需要filter(),你需要find(),这意味着它也不是真正需要记忆的东西。这可以简化为:

    const getCountryById = createSelector(
        [getCountries, (state, id) => id],
        (countries, id) => countries.find(c => c.id === id) || null
    )
    

    然后用作:

    const mapStateToProps = (state, ownProps) => {
        return  {
            country: getCountryById(state, ownProps.match.params.countryId)
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多