reactjs - 如何使用 Redux connect 传递 props

标签 reactjs react-native redux

我尝试使用 redux 属性传递字符串和子组件,如下所示。我收到错误“TypeError:无法读取未定义的属性circularImage”

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { View, Text, Image } from 'react-native'

// CircularImage.js
function CircularImage () {
  return (
    <Image source={this.props.imageSourceUrl} style={{width: 100, height: 100}} /> // Rounded Img
  )
}
CircularImage.propTypes = {
  imageSourceUrl: PropTypes.string.isRequired
}

function mapStateToProps1(state, ownProps) {
  return {
    imageSourceUrl: require('../images/icon.png')
  }
}

CircularImage = connect(mapStateToProps1)(CircularImage);

// ScreenHeaderWithImage.js
function ScreenHeaderWithImage () {
  return (
    <View style={{flex: 1, padding: 50}}>
      <View style={{marginBottom: 50}}>
        {this.props.circularImage}
      </View>
      <Text style={{ fontSize: 20 }}>{this.props.primaryHeadline}</Text>
      <Text style={{ fontSize: 10 }}>{this.props.secondaryHeadline}</Text>
    </View>
  )
}
ScreenHeaderWithImage.propTypes = {
  primaryHeadline: PropTypes.string.isRequired,
  secondaryHeadline: PropTypes.string, // Optional
}

function mapStateToProps2(state, ownProps) {
  return {
    primaryHeadline: 'Timothy Max',
    secondaryHeadline: 'Kenya',
    circularImage: CircularImage
  }
}

ScreenHeaderWithImage = connect(mapStateToProps2)(ScreenHeaderWithImage);

export default ScreenHeaderWithImage

最佳答案

当使用函数组件时,函数应该接收 props 作为参数。像这样

function ScreenHeaderWithImage (props) {
   ...
   <View style={{marginBottom: 50}}>
    {props.circularImage}
   </View>
   ....
}

关于reactjs - 如何使用 Redux connect 传递 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49533057/

相关文章:

javascript - React.js 语法错误

javascript - 在 React-Native 中按下按钮时不返回组件

javascript - 仅仅为了测试而创建不同的商店是错误的吗?

javascript - 试图访问 facebook graph api 回调中的生成器函数功能

redux - React Query/RTK 查询与 Redux 集成?

node.js - 如何在 gatsby 站点上加载 Mapbox?尽管在开发模式下工作,但构建成功但 map 不显示

javascript - 冒号前的参数

react-native - 运行应用程序时 react native (root 丢失)

javascript - 如何使用 JS 和 Lodash 重复一个元素 n 次

react-native - 在react-navigation TabNavigator中,如何设置Params