![](/img/trans.png)
[英]Why does the history.push not work with the button click? It simply does not forward me
[英]Why does my history.push work in one function but the other?
問題:我一直在嘗試在我的編輯 function 上使用 props.history.push。 我之前在我的 add function 上使用過它並且它有效。 我有相同的導入,唯一的主要區別是我也在我的編輯 function 中使用了 useEffect,而在我的添加 function 中我只有 useState。 還有我需要在編輯中訪問每個 id 的事實。
錯誤: TypeError:無法讀取未定義的屬性“歷史”
嘗試:我目前嘗試使用重定向,它只是重定向而不應用更改。 在按鈕 onClick 中使用 history.push 也可以,但它不應用我的更改。 我經常看到的另一個解決方案是在導入 useHistory() 之后 let history=useHistory() 但這給了我一個鈎子錯誤,我認為這可能是一個版本問題。 但是,我的另一個主要問題是為什么它在我的 Add() function 上有效。
Add.js 點擊Handler:
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 之外,代碼的 rest 也幾乎相同,因此我可以為字段提供默認值。 這真的讓我很困惑。 任何幫助,將不勝感激。 如果您需要更多詳細信息,請告訴我!
我在處理程序中傳遞了道具,而不是 Edit function 本身,這就是它不起作用的原因。 所以代碼應該是:
function handleSubmit(e) {
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');
}
這解決了我的問題,現在它可以工作了。 我很驚訝我之前沒有注意到這一點,因為我花了很長時間才弄清楚這一點。
嘗試使用window.history.push
而不是history.push
來使用 function。 If the default scope of your function is not window
, you must manually specify the window
scope in your function. 當從內聯script
標記調用外部腳本文件中的函數時,通常會出現此問題。
更新:將您的edit
代碼更改為
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);
history.push('/list');
}
function handleChange(e, field) {
e.preventDefault();
setState({
...state,
[field]: e.target.value,
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.