【问题标题】:ReactJS: Check if array contains value else appendReactJS:检查数组是否包含值,否则追加
【发布时间】:2018-08-06 04:32:12
【问题描述】:

我正在尝试检查 JSON 响应是否包含数组中已经存在的值,以及它是否没有添加它。我遇到的问题是了解如何在 reactjs 中处理这个问题。我在附加它之前检查它,但它不想工作。我试过传入用户 objectuser.id 但这些都失败了。下面的尝试无法编译,但它应该有助于理解我想要实现的目标。

代码:

componentWillMount() {
    fetch('http://localhost:8090/v1/users')
    .then(results => {
      return results.json();
    })
    .then(data => {
      data.map((user) => (
        if(userList.hasOwnProperty(user.id)) {
          userList.push({label: user.title, value: user.id})))
        }
    })
}

【问题讨论】:

    标签: arrays reactjs components


    【解决方案1】:

    我建议使用 reduce 将返回的数据转换为您想要的数组,然后将这些值添加到您现有的用户列表中:

    fetch('http://localhost:8090/v1/users')
    .then(res => res.json())
    .then(data => data.reduce((acc, user) => {
      const idList = userList.map(user => user.id);
      if (idList.indexOf(user.id) === -1) {
        acc.push({label: user.title, value: user.id})
      }
      return acc;
    },[]))
    .then(newList => userList = [...userList, ...newList]);
    

    【讨论】:

      【解决方案2】:

      map 返回结果数组,但您没有从中返回任何内容,您应该使用 forEach 另外您需要检查 userList 数组是否包含 id,因为您可以使用 findIndex

      你需要的是

      state = {
          userList: [];
      }
      componentDidMount() {
          fetch('http://localhost:8090/v1/users')
          .then(results => {
            return results.json();
          })
          .then(data => {
            const newUserList = [...this.state.userList];
            data.forEach((user) => { // use { here instead of 
              if(userList.findIndex(item => item.value === user.id) < 0) {
                newData.push({label: user.title, value: user.id})
              }
            })
            this.setState({userList: newUserList});
          });
      }
      render() {
         return (
             {/* map over userList state and render it here */}
         )
      }
      

      【讨论】:

        猜你喜欢
        • 2019-08-10
        • 2015-01-01
        • 2021-07-15
        • 1970-01-01
        • 2016-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多