【发布时间】:2021-06-10 00:53:18
【问题描述】:
问题: 我一直在尝试在我的编辑功能上使用 props.history.push。我以前在我的添加功能上使用过它并且它有效。我有相同的导入,唯一的主要区别是我也在我的编辑函数中使用了 useEffect,而在我的添加函数中我只有 useState。还有我需要在编辑中访问每个 id 的事实。
错误: TypeError:无法读取未定义的属性“历史”
尝试: 我目前尝试使用重定向,它只是重定向而不应用更改。在按钮 onClick 中使用 history.push 也可以,但它不会应用我的更改。我经常看到的另一个解决方案是在导入 useHistory() 之后 let history=useHistory() 但这给了我一个钩子错误,我认为这可能是一个版本问题。但是,我的另一个主要问题是为什么它在我的 Add() 函数上起作用。
Add.js 点击处理程序:
function handleSubmit(e) {
e.preventDefault();
axios({
method: "post",
url: "http://localhost:5000/add",
data: body,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
console.log(state);
props.history.push("/list");
}
这很好用。
编辑:
function handleSubmit(e, props) {
e.preventDefault();
axios({
method: "put",
url: "http://localhost:5000/update-list/" + testid,
data: body,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
console.log(state);
props.history.push('/list');
}
function handleChange(e, field) {
e.preventDefault();
setState({
...state,
[field]: e.target.value,
});
}
除了使用 useEffect 之外,其余代码也几乎相同,因此我可以为字段提供默认值。这真的让我很困惑。任何帮助,将不胜感激。如果您需要更多详细信息,请告诉我!
【问题讨论】:
标签: javascript reactjs react-router-dom browser-history react-functional-component