Мне нужно заполнить форму с помощью параметра 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>
</>
);
}
Реквизиты передаются родительским компонентом 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" }
]
Как я могу это исправить? Я думаю, что ошибка в getAuthorById в AuthorStore, но я не знаю, что именно делать.
Кроме того, извините за мой плохой английский sh, это мой первый вопрос здесь.