json - JSON.parse 与 redux 状态有关的问题
问题描述
使用 React 和 Redux,我正在调用getNoteById
它在note
.
我想 JSON.parsenote
变量,但如果它未定义,则将 setValue 设置为initialValue
我知道它将正确解析的位置。
我遇到的问题是,当我检查是否JSON.parse(note)
未定义时,我总是在 0 处得到相同的未定义索引错误。
不知道如何解决这个问题。当组件加载并被getNotesById()
调用时,notes
或者initialValue
应该在我调用时显示setValue
。
const TextEditor = ({ note, getNoteById, clearValues }) => {
const paramId = match.params.notes;
const [value, setValue] = useState();
useEffect(() => {
getNoteById(paramId);
if (JSON.parse(note) == undefined) {
setValue(initialValue);
} else {
setValue(JSON.parse(note));
}
return () => {
clearValues();
};
}, [paramId, value]);
return (
<div>
<h1> {value} </h1>
</div>
);
};
解决方案
您的效果缺少依赖项:clearValues、getNoteById 和 note。您应该跳过 setValue 到 initialValue 并这样做,const [value, setValue] = useState(initialValue);
因为效果在渲染之后运行,并且注释将在第一次渲染时未定义。检查 note 是否未定义if(note!==undefined){setValue(JSON.parse(note))}
。
您的代码应如下所示:
const TextEditor = ({ note, getNoteById, clearValues }) => {
const paramId = match.params.notes;
const [value, setValue] = useState(initialValue);
useEffect(() => {
getNoteById(paramId);
if(note!==undefined) {
setValue(JSON.parse(note));
}
return () => {
clearValues();
};
}, [clearValues, getNoteById, note, paramId, value]);
return (
<div>
<h1> {value} </h1>
</div>
);
};
我的猜测是,当注释加载并设置为 redux 状态时,您不想再次分派 getNoteById 。也许创造2个效果:
const TextEditor = ({ note, getNoteById, clearValues }) => {
const paramId = match.params.notes;
const [value, setValue] = useState(initialValue);
//dispatch getNoteById when param id changes
useEffect(() => {
getNoteById(paramId);
return () => {
//dispatch a cleanup action
clearValues();
};
}, [clearValues, getNoteById, paramId]);
//set the note to it's parsed json when it changes
// and is not undefined
useEffect(() => {
if (note !== undefined) {
setValue(JSON.parse(note));
}
}, [note]);
return (
<div>
<h1> {value} </h1>
</div>
);
};
推荐阅读
- flutter - Flutter BLoC:管理主要数据类型的状态
- asp.net - 为什么我的图像不会保存在我的数据库中?
- database - 尝试从优势数据库迁移到 fireac
- javascript - 如何使用 ngDowngrade 将参数从 AngularJS 组件传递到子 Angular 2 组件?
- midi - MIDI 中的拍号元信息
- java - 如何在重定向中添加授权标头(Spring Security)
- ruby - 如何使用 Azure 泊坞窗 API
- javascript - 如何解决错误的请求
- ios - 快速找到自定义对象数组中最接近的值
- bash - 比较两个文本文件并根据 bash shell 脚本中的键打印差异