繁体   English   中英

无法从 redux state 渲染道具值

[英]Cannot render value of props from redux state

我有一个 redux state 工作正常,因为我的数据在 redux 存储中。 我可以使用 console.log(this.props) console.log 将其注销,但我似乎无法将其渲染出来。 它返回此错误:

TypeError: Cannot read property 'somevalue' of undefined

通常我会 map 通过带有 html/jsx 块的 static 块的道具,但我需要这是不同的 html 每个循环的值,所以我试图直接插入标记。 谁能指出我正确的方向?

import React, {Component} from 'react';
import { connect } from 'react-redux';

class UnitClass extends Component {
    state = {
        unit: {}
    }

    render() {
        console.log('Props is:', this.props); // shows correct values
        return (
            <ul>
               <li>{this.props.unit.somevalue.value1}</li>
               <li>{this.props.unit.somevalue.value2}</li>
               <li>{this.props.unit.somevalue.value3}</li>
               <li>{this.props.unit.somevalue.value4.someothervalue}</li>
            </ul>
        );
    }
}

const mapStateToProps = state => ({
    unit: state.setUnit.unit,
});

export default connect(mapStateToProps)(UnitClass);

尝试这样的事情

 render() {
        console.log('Props is:', this.props); // shows correct values
        const {unit} = this.props;
        return (
            <ul>
            {unit.somevalue && unit.somevalue.map((value)=>{
            return value.someothervalue? <li>{value.someothervalue}</li>: <li>{value}</li>})
            }  
            </ul>
        );
    }

注意:对于条件渲染,您可以使用ternary operator ,如果您必须处理嵌套条件渲染,那么我会推荐Higher Order Components ,然后可能是这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM