React redux传奇多重渲染



我是新手,我遇到了多个渲染的问题,我只是想知道我做得是否正确,所以我在我的列表组件中调度了一个操作来获得一个注释列表,现在看起来是这样的:

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>
)
}

这个组件在另一个容器类中连接,但这是不相关的,所以这个组件渲染了4次,两次没有useEffect钩子,还有两次有了它,我想实现的是,我需要在每个注释的对象中添加一个项目(即模式:标题模式(,这个组件的状态可以很好地使用这个代码,至于我为什么在一个状态中添加这个模式,是因为我想在音符数组中更改它,这样我就可以更改每个音符的视图模式,但正如我所提到的,这个组件渲染了4次,在我看来,这绝对不是正确的方式。

如果你有时间,请帮忙。

我们可以通过使<Note />组件中的显示模式状态自行实现注释列表的显示,这样更改模式就不会影响其他注释,这样我们就不会有额外的重新渲染,而且使用这种方法还可以在本地修改注释,而无需将其发送到商店,然后我们可以在最后更新商店,从而获得性能。所以基本上这就是方法(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>
);
}

最新更新