Redux-ES6更新阵列中的对象元素

时间:2018-11-08 21:07:50

标签: javascript reactjs ecmascript-6 redux react-redux

当在数组内的对象内添加元素时,我偶然发现了一个问题。我想做的就是添加元素isFavorite: true。我目前正在尝试通过以下方法做到这一点:

{ 
    ...state, 
    list: state.list.map(item => 
        item.id === action.payload.libraryContentId ? 
        { ...item, isFavorite: true } 
        : item) 
}

有效负载包含以下对象:

{
    id: 1,
    name: 'Name',
    libraryContentId: 3
}

但是以上内容似乎并未更新项目并添加元素。你们有什么建议?

编辑:更多代码示例。

操作:

try {
    const response = await axios.post(URL, {params});
    dispatch({ type: ADD_FAVORITE, payload: response.data });
catch (error) {
    dispatch({ type: ERROR });
}

响应数据:

{
    id: 117
    libraryConntentId: 245
}

列出项目示例:

{
    id: 245,
    name: 'Name',
    isFavorite: false
}

谢谢!

1 个答案:

答案 0 :(得分:1)

也许是这样(检查testMethod):

class Hello extends React.Component {
	constructor(props){
  	super(props);
    
    
    let testData = [
    	{
      	id: 1,
        name: 'Name1',
        isFavorite: false
      },
      {
      	id: 2,
        name: 'Name2',
        isFavorite: false
      },
      {
      	id: 3,
        name: 'Name3',
        isFavorite: false
      },
      {
      	id: 4,
        name: 'Name4',
        isFavorite: false
      },
      {
      	id: 5,
        name: 'Name5',
        isFavorite: false
      }]
    
    this.state = {
    	boolvar: true,
        numbar: 2,
    	list: testData
    }
   	this.testMethod = this.testMethod.bind(this);
    console.log("Original state");
    console.log(this.state);
  }
  
  testMethod(){
  		 let testAction = {
		payload: {
    	libraryContentId: 3
     }
	}
  
   this.setState((prevState, prevProps) => {
      return {
       list: [...prevState.list.map(item => item.id === testAction.payload.libraryContentId? {...item, isFavorite: true}: item)]
       }});
   }
  render(){
  	console.log(this.state);
    return (<div><button onClick={() => {this.testMethod()}}>Test It</button></div>);
  }
  
   
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>