【问题标题】:Update state of only the clicked element仅更新被点击元素的状态
【发布时间】:2018-01-24 19:18:41
【问题描述】:

所以我的代码是:

export default class MyClass extends Component {

  constructor(props) {
    super(props);
    this.state = {
        data: [
          {id: 101, name:"One", thevalue:11},
          {id: 102, name:"Two", thevalue:22},
          {id: 103, name:"three", thevalue:33}
        ]
    }
  }

  handleOnPress() {
    << HOW DO I CODE THIS ?? >>
    I want to increase the number count in thevalue of the pressed item
  }

  render() {
      return(
        <FlatList
            data = {this.state.data}
            renderItem = {
                ({item}) => 
                <TouchableOpacity onPress={this.handleOnPress} >
                    <Text> {item.name} + {item.thevalue} </Text>
                </TouchableOpacity>
            }
        />
    )
  }
}

我希望能够增加仅单击项目的thevalue 的计数。所以我应该做一个setState 对吗?但是我怎么知道我需要在哪个项目上运行它?我需要将点击的项目的id 传递给函数吗?如果是,我该怎么做?

非常感谢。

更新1:

handleOnPress(id) {
      this.setState({
        thevalue: this.state.thevalue+1
    });
}

【问题讨论】:

  • 您可以在onPress 中提供item 吗?例如:{this.handleOnPress(item)} 或类似?
  • @JeffHuijsmans 你不能这样称呼它,否则将在渲染每个项目时调用 handleOnPress。你需要按照我的回答做点什么:)
  • @MattDerrick 很好,谢谢!我在想另一个框架:)
  • 为什么不创建一个项目组件并在其中按下处理?在 MyClass 中只渲染列表。

标签: javascript reactjs react-native


【解决方案1】:

您可以将id 传递给onPress,然后更新对应的thevalue

export default class MyClass extends Component {

  constructor(props) {
    super(props);
    this.state = {
        data: [
          {id: 101, name:"One", thevalue:11},
          {id: 102, name:"Two", thevalue:22},
          {id: 103, name:"three", thevalue:33}
        ]
    }
  }

  handleOnPress(id) {
    let {data} = this.state;
    let idx = data.findIndex(x => x.id == id);
    data[idx].thevalue ++;
    this.setState({data});
  }

  render() {
      return(
        <FlatList
            data = {this.state.data}
            renderItem = {
                ({item}) => 
                <TouchableOpacity onPress={() => this.handleOnPress(item.id)} >
                    <Text> {item.name} + {item.thevalue} </Text>
                </TouchableOpacity>
            }
        />
    )
  }
}

【讨论】:

  • 我收到了undefined is not an object (evaluating 'data[idx].thevalue') 我关注了你的代码
  • onPress={(item) =&gt; this.handleOnPress(item.id)} onPress 函数你改了吗?
  • 没有。和这里完全一样。为 idx 给出相同的错误
  • 你能退出idxdata看看哪个是null吗?
  • console.log(idx) 为点击的任何项目返回1
【解决方案2】:

你必须给它一个参数,这样我们才能知道要增加什么项目:

onPress={this.handleOnPress.bind(this, item.id)}
...
handleOnPress(id) {
    // increment id
}

或者这更具可读性但做同样的事情:

onPress={() => this.handleOnPress(item.id)}

【讨论】:

  • 我有我的功能:this.setState({thevalue: this.state.thevalue+1}); 但不工作。
  • 您是在使用“thevalue”进行更新吗?您需要更新 'data[X].thevalue' 其中 X 是具有相同 ID 的对象的位置。
  • 我做到了。关注stackoverflow.com/questions/45717081/…,但它没有实时更新数据。我必须在页面中保存一些东西,热重载就可以了。我希望实时更新数据。
猜你喜欢
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多