根据其中一个属性删除数组中的对象

时间:2018-05-07 13:25:43

标签: javascript reactjs react-native

我正在尝试操作状态中的组件数组,我希望能够根据它的id属性删除每个组件。每当我创建组件时动态传递id时,我无法弄清楚如何定位组件。

constructor(props) {
    super(props);
        this.state = {
        counters: 0, // counters count    
        countersArr: []
    }}

render() {

        let countersArrCop = this.state.countersArr;
        let counterIndex;

    onAddCounterHandler = () => {

        const id = new Date().getTime()
        console.log(this.state.countersArr.length)
        console.log(counterIndex)
        countersArrCop.push( // push new counter to the counters holder
            <Counter 
                style={styles.countersContainer} 
                key={id}
                id={id}
                remove={() => removeCounterHandler(id)}
            />
        )

        this.setState({
            countersArr: countersArrCop,
        })
        console.log(id)
    }

    // remove counter
    removeCounterHandler = (id) => {
        console.log(id)
        const countersArr = this.state.countersArr.slice(); // Local copy to manipulate
        this.setState({ countersArr: countersArr.filter(counter => counter.id !== id) });
      }

        return (

            <View style={styles.container}>

                <View style={styles.addBtnContainer}>
                    <Button 
                        onPress={onAddCounterHandler} 
                        title={'add Counter'}
                    />
                </View>

                {
/* return each individual counter from the array by using 'map' */
}
                <View style={styles.container}> {
                    this.state.countersArr.map((counter) => {
                        return counter;
                    })
                }
                </View>

            </View>
        );

更新代码*** id === undefined ..为什么?

2 个答案:

答案 0 :(得分:2)

首先,非常不鼓励在render()中放置逻辑代码。渲染应该只渲染,任何其他任务应该在它们应该的位置。请注意,每次组件重新渲染时,渲染块中的​​所有代码都会被称为因此,应该将这些处理程序声明为组件类中的方法,并使用渲染中的正确挂钩,如{{1}并且不要忘记绑定这样的onClick()上下文,以便在方法中保留对组件类的this引用:

this

第二,当你可以将ID存储在一个数组中时,你的状态会膨胀你的状态:

<Button onClick={this.onAddCounterHandler.bind(this)} />

然后只映射该数组并返回如下所示的组件:

onAddCounterHandler() {
    const { countersArr } = this.state
    const id = new Date().getTime()
    this.setState({
        countersArr: [...countersArr, id],
    })
}

请注意,在jsx中,此语句应括在大括号{}

然后是你的过滤功能:

{ this.state.countersArr.map(id=>
    <Counter 
        style={styles.countersContainer} 
        key={id}
        id={id}
        remove={this.removeCounterHandler.bind(this, id)}
    />
) }

最后,永远不要将setState放在渲染

尝试一下,让我知道它是怎么回事:)

答案 1 :(得分:0)

你可以做这样的功能:

removeCounterHandler (id) {
  const countersArr = this.state.countersArr.slice(); // Local copy to manipulate
  this.setState({ countersArr: countersArr.filter(counter => counter.id !== id) });
}
相关问题