首页 > 解决方案 > 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>
  );
};

标签: jsonreactjsparsingredux

解决方案


您的效果缺少依赖项: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>
  );
};

推荐阅读