reactjs - 将参数传递给 `connect()` 中的 mapStateToProps

标签 reactjs react-native redux react-redux

如何将参数传递给 mapStateToProps()

EG:

const mapStateToProps = (state, dimenType: string) => {

  var jsonVariable = {}
  for(var i=1; i <= 3; i++) {
    jsonVariable[dimenType + i] = dimenType + i
  }
  console.log(jsonVariable)
  return {
    width1: state.get('width').get('width1').toString(),
    width2: state.get('width').get('width2').toString(),
    width3: state.get('width').get('width3').toString()
  }
}

这是我不确定的一点:

Width = connect(
  mapStateToProps(/*redux store goes here somehow*/, 'thickness'),
  mapDispatchToProps
)(Width)

我希望 Redux 存储仍然传递到 mapStateToProps 中,但也传递 "thickness"。如何在 connect() 函数中执行此操作?

最佳答案

connect的第二个参数是 ownProps这是传递给 Component 的 props 。因此,根据您的情况,您可以像这样使用它:

const mapStateToProps = (state, ownProps) => {
  let jsonVariable = {}
  for(var i=1; i <= 3; i++) {
    jsonVariable[dimenType + i] = ownProps.dimenType + i
  }
  console.log(jsonVariable)
  return {
    width1: state.get('width').get('width1').toString(),
    width2: state.get('width').get('width2').toString(),
    width3: state.get('width').get('width3').toString()
  }
}

我假设您正在像这样创建组件:<Width thickness={10}/>

关于reactjs - 将参数传递给 `connect()` 中的 mapStateToProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42943278/

相关文章:

reactjs - react : Expected an assignment or function call and instead saw an expression

android - React Native Android - 如何仅在设备上以 Debug模式运行?

android - 由于 minSdkVersion 正在努力让 Android 构建工作

javascript - 没有赋值运算符的变量名周围的大括号是什么意思

react-native - 热重载应该如何在 native react 中工作?

javascript - react 堆 :mapStateToProps not rendering the component on state change

javascript - 如何以编程方式触发输入[type ="file"]而不涉及实际点击?

javascript - 在redux中使用combineReducers时如何修复shape AssertionError?

javascript - 可以使用对象方法或 JavaScript 中的其他方式进一步优化吗?

css - React-Native 文本不在两行