【问题标题】:Properly mapping stateToProps with react-redux使用 react-redux 正确映射 stateToProps
【发布时间】:2018-12-04 02:46:21
【问题描述】:

我是项目的 react-redux 范例的新手,我对将状态映射到道具的概念有点困惑。我创建了一个带有初始值的商店:

export function initialState() {
    return { priceRange:[0,10000] }
}

然后在我的子组件中我 mapStateToProps 像这样:

const mapDispatchToProps = { onPriceRangeChange }
const mapStateToProps = {priceRange}  = ({
    value:priceRange
})

export default connect(mapStateToProps, mapDispatchToProps)(HomeMap)

问题在于它收到了'priceRange' is not defined no-undef 错误。有什么想法吗?

【问题讨论】:

  • 使用 ({priceRange}) => 将道具解构为箭头函数。
  • 您的应用是否包含在 react-redux <Provider> 组件中?
  • 我的应用程序的根被包裹在<Provider store={store}>..</Provider>

标签: reactjs redux


【解决方案1】:

您在状态的= 之后缺少>

const mapDispatchToProps = { onPriceRangeChange }
const mapStateToProps = state => ({
   value: state.reducerFile.priceRange
})

export default connect(mapStateToProps, mapDispatchToProps)(HomeMap)

如果这仍然不起作用,如果您正在使用 combineReducers(),请参见下文;


combineReducers()

你用的是reduxcombineReducers()方法吗?如果是这样,那么您将需要更深入地了解自己的价值观。

// reducer.js
export function initialState() {
    return { priceRange:[0,10000] }
}

//store.js
import { initialState } from './reducer.js';
import { combineReducers, createStore } from 'redux';

export default createStore(
  combineReducers({
    reducerFile: initialState
  })
);

然后在你的子组件中,你会得到这样的

const mapDispatchToProps = { onPriceRangeChange }
const mapStateToProps = state  => ({
   value: state.reducerFile.priceRange
})

export default connect(mapStateToProps, mapDispatchToProps)(HomeMap)

【讨论】:

    【解决方案2】:

    这是因为你必须定义你的mapStateToProps,如下:

    const mapStateToProps = ({ priceRange }) => ({
        value: priceRange
    })
    

    同理:

    const mapStateToProps = state => ({
        value: state.priceRange
    })
    

    这种技术被称为Destructuring assignment

    解构赋值语法是一个 JavaScript 表达式 可以从数组中解压缩值,或从 对象,转换成不同的变量。

    【讨论】:

      【解决方案3】:

      错过mapStateToProps

      添加:

      export default connect(mapStateToProps, mapDispatchToProps)(HomeMap)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-03
        • 2020-11-15
        • 1970-01-01
        • 2012-12-22
        • 1970-01-01
        • 2020-01-08
        • 2020-02-25
        • 2021-12-10
        相关资源
        最近更新 更多