基于该对象的键的值来对象对象,该对象是数组中的元素

时间:2017-09-29 20:42:56

标签: reactjs react-native redux react-redux

如何基于该对象的键值来定位哪个对象,该对象是数组中的元素。

减速机:

const initialState = {
    posts: []
}


export default function newData (state = initialState, action) {
  switch (action.type) {
    case "updateNumber":
      return {
        ...state,

        /* How to determine which object's number I should update? */
        /* The payload is the id */
        number: this.state.number ++ // <== need help here.
      }
    default:
      return state
  }
}

API调用返回的数据将附加到帖子:

帖子:

[
  {
    id: '1',
    name: 'Name One',
    number: 11
  },
  {
    id: '2',
    name: 'Name Two',
    number: 22
  },
  {
    id: '3',
    name: 'Name Three',
    number: 33
  }

]

在组件I中渲染它:

class Posts extends Component {

    renData () {
      console.log("ThePosts: ", this.props.posts);
      return posts.map((post, postIndex) => {
        return (
            <View key = {postIndex}>
                <TouchableOpacity
                    onPress={() => updateNumber(post.id)} 
                >
                    <Text> {post.number} </Text>
                </TouchableOpacity> 
            </View>
        )
      });
    }

    render(){
      return(
        <View style={style.container}>
            {this.renData}
        </View>
      )
    }

}

function mapDispatchToProps(dispatch) {
  return {
    updateNumber: (id) => {
      dispatch(updateNumber(id))
    }
  }
}

function mapStateToProps(state) {
  return {
      posts: state.posts,
  }
}

export default connect( mapStateToProps, mapDispatchToProps ) ( Posts );

如何确定要更新哪个对象number

注意:我尝试了this approach,但我发现将API调用数据附加到对象非常困难。数组更容易。

请协助。

1 个答案:

答案 0 :(得分:1)

假设updateNumber实际上只是递增数字,您必须首先使用id找到要在reducer中更新的数组中对象的索引。然后,您可以创建一个新数组,用增量对象替换该对象:

export default function newData (state = initialState, action) {
  switch (action.type) {
    case "updateNumber": {
      const { posts } = state;
      // find object to update
      const index = posts.findIndex(({ id }) => id === action.id);

      if (index > -1 ) {
        // create new object with existing data and increment number
        const updatedData = {...posts[index]};
        updatedData.number++;

        // return new posts array that replaces old object with incremented object at index
        return { posts: [...posts.slice(0, index), updatedData, ...posts.slice(index + 1)]};
      }

      // return state if no object is found
      return state;
    }
    default:
      return state
  }
}