React redux saga 多重渲染

React redux saga multiple renders

我是 React 的新手,我遇到了多个渲染的问题,我只是想知道我是否做对了,所以我在我的列表组件中发送了一个操作来获取注释列表现在看起来像这样:

import React, {useState, useEffect} from 'react';

export default function NoteList (props){


const [ noteList, updateNoteList ] = useState([]);

useEffect(()=>{
    updateNoteList(
        props.noteList.map(note => {
            return {...note, mode : 'title-mode'};
        })
    )
},[props.noteList])



console.log(noteList);
return (
    <div>

    Notes come here

    </div>
  )

}

这个组件连接在另一个容器中 class 但那是无关紧要的,所以发生的是这个组件渲染了 4 次,两次没有 useEffect 钩子,另外两次有它,我想要实现的是我需要在每个音符的 object 中添加一个项目(即模式:title-mode),处于此组件的状态,该组件可以正常使用此代码,至于为什么我要在 a 中添加此模式state 是我想在 note 数组中更改它,以便我可以更改每个 note 的视图模式,但是这个组件呈现了 4 次,正如我提到的,在我的脑海中,这不是正确的方法。

有空请帮忙

我们可以通过在 <Note /> 组件中创建一个 display-mode 状态来实现笔记列表的显示它自己所以改变模式不会影响其他笔记,这样我们就不会有额外的 re-renders,同样使用这种方法也将允许在本地修改笔记而不将其分派到商店然后我们可以在最后更新商店以获得性能。 所以基本上这就是方法 (codesandbox):

const Note = ({ title, content }) => {
  const [isExpanded, setIsExpanded] = useState(false);

  return (
    <div
      style={{ border: "1px solid", margin: 5 }}
      onClick={() => setIsExpanded(!isExpanded)}
    >
      {!isExpanded ? (
        <div>
          <h2>{title}</h2>
        </div>
      ) : (
        <div>
          <h2>{title}</h2>
          <p>{content}</p>
        </div>
      )}
    </div>
  );
};

function App() {
  // this is the notes state, it could be coming from redux store so
  // we could interact with it (modifying it if we need)
  const [notes, setNotes] = React.useState([
    { id: 1, title: "note 1", content: "this is note 1" },
    { id: 2, title: "note 2", content: "this is note 2" }
  ]);

  return (
    <div className="App">
      {notes.map((note) => (
        <Note key={note.id} {...note} />
      ))}
    </div>
  );
}