javascript - 使用 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 中,但我不知道该怎么做。
另外,对不起我的英语不好,这是我在这里的第一个问题。
解决方案
推荐阅读
- javascript - 在ajax回调函数javascript中执行乱序
- python - 增加饼图 matplotlib 中标签的字体大小
- powershell - 使用powershell删除Excel中的第一个单元格
- r - 将图例插入与因子相关的图中
- python - ./getXml.py:第 3 行:意外标记 `(' 附近的语法错误
- javascript - 如何在博主的相关帖子小部件中使用第一张图片,如缩略图?
- angularjs - Angular JS 获取 HTTP 请求参数
- arrays - 具有包含引用的可能变体的枚举数组
- vb.net - 如何让我的表单填满当前屏幕上的整个屏幕
- hyperledger-fabric - Hyperledger Composer 建模语言,如何将概念导入另一个模型文件