首页 > 解决方案 > 使用 ReactJS 和 Flux 通过 URL :id 填充表单

问题描述

我需要通过 URL :id 参数填充表单,以便用户可以编辑作者姓名。当我单击指向作者姓名的链接时,出现以下错误:

单击作者姓名时出现错误

作者表单的视图在 AuthorForm.js 中,就像这样:

function AuthorForm(props) {
  return (
    <>
      <form onSubmit={props.onSubmit}>
        <TextInput
          id="name"
          name="name"
          label="Name"
          value={props.author.name}
          onChange={props.onChange}
          error={props.errors.name}
        />
        <input type="submit" value="Save" className="btn btn-primary" />
      </form>
    </>
  );
}

props 由父组件 ManageAuthorPage.js 传递

const ManageAuthorPage = (props) => {
  const [errors, setErrors] = useState({});
  const [redirectNotFound, setRedirectNotFound] = useState(false);
  const [authors, setAuthors] = useState(authorStore.getAuthors());
  const [author, setAuthor] = useState({
    id: null,
    name: "",
  });

  useEffect(() => {
    authorStore.addChangeListener(onChange);

    const id = props.match.params.id;
    if (id === undefined || authors.length === 0) {
      authorActions.loadAuthors();
    } else if (id) {
      setAuthor(authorStore.getAuthorById(id));
    }

    return () => {
      authorStore.removeChangeListener(onChange);
    };
  }, [props.match.params.id, authors.length]);

  function onChange() {
    setAuthors(authorStore.getAuthors());
  }

  return (
    <>
      <h2>Manage Author</h2>
      <AuthorForm
        errors={errors}
        author={author}
        onChange={handleChange}
        onSubmit={handleSubmit}
      />
    </>
  );
};

export default ManageAuthorPage;

我也在使用 Flux,所以我的 authorStore 看起来像这样:

class AuthorStore extends EventEmitter {
  /**this will allow React components to subscribe to our store
   * so they're notified when changes occur */
  addChangeListener(callback) {
    this.on(CHANGE_EVENT, callback);
  }

  /** this will allow React components to unsubscribe from our store*/
  removeChangeListener(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }

  emitChange() {
    this.emit(CHANGE_EVENT);
  }

  getAuthors() {
    return _authors;
  }

  getAuthorById(id) {
    return _authors.find((author) => author.id === id);
  }
}

我也有 authorAPI,它也有一些方法:

export function getAuthorById(id) {
  return fetch(baseUrl + id)
    .then((response) => {
      if (!response.ok) throw new Error("Network response was not ok.");
      return response.json().then((authors) => {
        if (authors.length !== 1) throw new Error("Author not found: " + id);
        return authors[0];
      });
    })
    .catch(handleError);
}

我的作者数据如下所示:

"authors": [
    { "id": 1, "name": "Cory House" },
    { "id": 2, "name": "Scott Allen" },
    { "id": 3, "name": "Dan Wahlin" }
  ]

我怎样才能解决这个问题?我认为错误出现在 AuthorStore 的 getAuthorById 中,但我不知道该怎么做。

另外,对不起我的英语不好,这是我在这里的第一个问题。

标签: javascriptreactjsflux

解决方案


推荐阅读