首页 > 解决方案 > 具有动态(基于 uid)路径的 React-Redux mapStateToProps

问题描述

我是 React 和 React-Redux 的新手。我正在尝试根据用户 ID 使用动态路径传递“mapStateToProps”。使用的基本代码如下:

const mapStateToProps = (state) => {

    console.log(state);
    console.log(state.firebase.auth.uid); <===== THIS DISPLAYS THE USERS ID, PROVING THE PATH EXISTS

    return {

        courses: `state.firestore.ordered.${state.firebase.auth.uid}`, <======= THIS LINE IS AN ERROR EVEN THOUGH THE PATH EXISTS

    }
}

如果我手动输入用户 ID,代码可以正常工作。假设用户 ID 是“12345”,然后将该行替换为

courses: state.firestore.ordered.12345, <======= THIS LINE WOULD WORK

任何关于为什么这不起作用的澄清以及使这项工作的替代方法将不胜感激!

标签: reactjsreact-reduxmapstatetoprops

解决方案


如果要访问 JS 对象中的动态属性,则需要使用方括号

    courses: state.firestore.ordered[state.firebase.auth.uid]

推荐阅读