0

我在页面上有三个按钮,当单击任何按钮时,我想从按 id 过滤的商店中获取所选值(在减速器中完成)。我正在尝试将 redux 与 mapStateToProps 和 mapDispatchToProps 模式一起使用,但看起来当我在单击任何按钮后尝试从商店访问当前选定的值时,它不会在控制台中反映正确的值。这不是如何使用“this.props.anyPropValue”吗?你能帮助澄清我的例子中有什么问题吗?第一次单击任何按钮时打印默认值,再次单击将打印先前单击的按钮值而不是当前值。

这是我为上面创建的简单应用程序的沙盒链接

代码的沙箱链接

4

1 回答 1

1

您编写的大多数代码都是正确的,如果您希望在调用操作后立即看到更新的输出,那么它将无法正常工作

onGetCountryById(id) {
    this.props.fetchCountryById(id);
    console.log(this.props.country); // This will gives you the current country (We just update the state, but still that value didn't update the component)
}

尝试在下面的 html 中打印国家/地区的值,您会看到它正在更新

{this.props.country === null ? "default" : this.props.country.name}

在减速器中,您可能需要进行此更改

case CountryActions.FETCH_COUNTRY_BY_ID:
    return {
        ...state,
        country: state.countries.find((item) => item.id === action.id) // use find instead of filter
    };

并将国家的初始值设置为null

const initCountriesState = {
    country: null,
    countries: [
        ....
    ]
};

这是更新的沙箱

于 2021-02-28T06:59:29.130 回答