[英]Redux - ES6 Updating Object Element in Array
當在數組內的對象內添加元素時,我偶然發現了一個問題。 我想做的是添加元素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
}
謝謝!
也許是這樣的(檢查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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.