簡體   English   中英

在 React Native 中更新 object 的嵌套 object 內的值

[英]Updating value inside nested object of object in React Native

我有 state 設置如下

const [stories, setStories] = useState([]);

我從數組中的 API 中獲取數據,並在數組中獲取 map 並將使用 setStories 設置為:

setStories(prevState => prevState.concat({user: {name: 'XYZ', profile: 'ABC', stories: [{id: 1, image: 'testing'}];

上面的代碼工作正常,但我被卡住了,如果 id 與獲取的數據不匹配,我必須連接最新的故事。 我嘗試了以下解決方案,但沒有幫助:

stories.map(story => {
if(story && story.hasOwnProperty(key)){
//where above key is the user key fetched from the another API, i.e., user key
story?.[key].stories.map(storedStory => 
id(storedStory.id !== fetchedStory.id){
story?.[key].stories.concat({story})}

但上面的代碼不起作用,因為它只會改變 state 並且避免重新渲染。 尋找一種干凈有效的方法來克服這個問題。 謝謝

如果沒有完整的示例,很難說出您要完成的工作。 但我認為您的主要問題是您沒有使用map的返回值,並且從命名看來您添加了錯誤的元素。

這將有助於首先簡化。

  const newState = stories.map(story => {
    if (story?.hasOwnProperty(key)) {
      const found = story[key].stories.find(s => s.id === fetchedStory.id);

      if (found) {
        return story;
      } else {
        // Let's make a new object with the fetchedStory
        // appended into THIS user's stories
        return {
          ...story,
          [key]: {
            ...story[key],
            stories: [
              ...story[key].stories,
              // This is supposed to be fetchedStory
              // not `story` right??
              fetchedStory,
            ]
          }
        }
      }
    } else {
      return story;
    }
  });

  setStory(newState);

編輯:您很難表達您的業務邏輯,並且數據結構的復雜性無濟於事。 所以繼續簡化,將復雜的語法封裝成函數,然后簡單地表達你的業務邏輯。 IE,

const appendStory = (originalObject, userId, storyToAppend) => {
  return {
    ...originalObject,
    [userId]: {
      ...originalObject[userId],
      stories: [
        ...originalObject[userId].stories,
        storyToAppend,
      ]
    }
  }
};

const userExistsInList = (users, user) => {
  return users?.hasOwnProperty(user);
}

const newStoryAlreadyInStories = (stories, newStory) => {
  return stories.find(s => s.id === newStory.id);
}

const newState = stories.map(story => {
  if (userExistsInList(story, key)) {
    
    const found = newStoryAlreadyInStories(story[key].stories, fetchedStory);

    if (found) {
      // User is already in state and the new story is already in the list
      // Add business logic here
    } else {
      // User is already in state and the new story
      // is not in their list
      // Add business logic here
    }
  } else {
    // User is not in the list yet
    // Add business logic here
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM