【问题标题】:Inserting an item in array every X places and "attempted to assign to readonly property"每 X 个位置在数组中插入一个项目并“尝试分配给只读属性”
【发布时间】:2017-05-13 20:57:47
【问题描述】:

我有一个来自服务器的对象数组。我用它在屏幕上显示卡片。我想每 X 卡插入一张“广告卡”。我以为我已经使用以下代码在网络上完成了此操作,但它似乎不适用于我的 react-native 应用程序。

class DeckArea extends React.Component {
    constructor(props){
        super(props);
    }
    render(){

        let { data, likeJob } = this.props;

        // place an object into the array of jobs data
        data.jobs.forEach((item, i) => {
            let remainder = i%4;        
            if (remainder === 0) {
                console.log(remainder === 0)
                data.jobs.splice(i, 0,{ isAd: true, _id: uuidV4() })
            }
        });


        return (
            <View style={styles.container}>
                <Swipe
                  data={data.jobs}
                  renderCard={(job) => {
                    //check if isAd === true, 
                    // if so, show the AdCard not the deck card
                    if (job.isAd) {
                        return <AdCard adsManager={adsManager} />
                    }
                    return <DeckCard job={job} isLikedCard={false} />
                  }}
                />
            </View>
        );
    }
}

我已经做了一些快速测试,问题肯定在这里发生:

           data.jobs.forEach((item, i) => {
                let remainder = i%4;        
                if (remainder === 0) {
                    console.log(remainder === 0)
                    data.jobs.splice(i, 0,{ isAd: true, _id: uuidV4()})
                }
            });

导致“试图分配给只读属性”

其他资源:

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    首先,通过使用data.jobs.splice() 插入原始作业数组,您正在修改通过道具传递的数组,这被认为是不好的做法。

    相反,您应该创建一个包含作业添加的新数组。示例代码:

    // Will show an add after each 4 jobs
    const jobsWithAds = data.jobs.reduce((accumulator, job) => {
      const add = { isAd: true, _id: uuidV4() }
      const remainder = accumulator.length % 5; // 5 is needed to include job ad
    
      // Additional check is required to skip first add
      if (remainder === 0 && accumulator.length > 0) {
        accumulator.concat(add);
      }
    
      // Add an ad after first 4 jobs, which have no ad
      if (accumulator.length === 4) {
        accumulator.concat(add);
      }
    
      accumulator.concat(job);
    }, [])
    

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 2020-04-08
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多