【问题标题】:React Native map() and JSX elements in arrayReact Native map() 和数组中的 JSX 元素
【发布时间】:2020-10-17 02:16:39
【问题描述】:

尝试使用 map() 在 React Native 中渲染一个 JSX 元素数组(this.state 中的 tableData),但我在控制台上得到了一个包含未定义元素的数组。

这是我的代码:

const TVSHOWIMAGETITLES = [
    MoneyHeist, BreakingBad,
    MoneyHeist, BreakingBad,
    MoneyHeist, BreakingBad,
    MoneyHeist, BreakingBad,
    MoneyHeist];

class HashTablesScreenTwo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            fiveShows: this.props.route.params.selectedShows,
            tableHead: ['Week', 'TV Shows'],
            tableWeeks: [1, 2, 3, 4, 5],
            tableData: []
        }
    }

renderTableData(){
        const jsxArray = this.state.tableWeeks.map((i)=>{this.renderTVShowImageTitle(i-1)})
        console.log(jsxArray)
        console.log(this.state.tableWeeks)
        return{
            tableData: jsxArray
        }
    }
    renderTVShowImageTitle(i) {
        let index = this.state.fiveShows[i];
        return (
            <TVShow
                id={index}
                imageSource={TVSHOWIMAGETITLES[index]}
                onClick={() => 1}
            />
        )
    }

render() {
        const state = this.state;
        { this.renderTableData() }
        return (
            <View>

                <Text>
                    Because you're ambitious,
                    you have decided to binge watch the shows at a rate of one show per week.
                    Here's how your planned schedule looks based on the order you have selected the shows:
                </Text>

                <View style={styles.container}>
                    <Table borderStyle={{ borderWidth: 2, borderColor: '#c8e1ff' }}>
                        <Row data={state.tableHead} style={styles.head} textStyle={styles.text} />
                        <Col data={state.tableWeeks} />
                        <Col data={state.tableData} />
                    </Table>
                </View>
        );
    }
}

如果有人能指出我在这里做错了什么,不胜感激。谢谢!

【问题讨论】:

    标签: javascript arrays react-native jsx


    【解决方案1】:

    您需要从 map 函数中删除花括号,如下所示:

    const jsxArray = this.state.tableWeeks.map((i)=> this.renderTVShowImageTitle(i-1))
    

    或者使用return语句:

    const jsxArray = this.state.tableWeeks.map((i)=> { 
                                    return this.renderTVShowImageTitle(i-1)
                                })
    

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多