![](/img/trans.png)
[英]react native: what is the way to transform the class component to a function component with hooks?
[英]Is there a way to put react hooks in a function that's not function component?
我正在嘗試創建一個 function ,它不是可在特定事件上調用的組件或掛鈎。 假設我有一個簡單的 function 使用 axios 發布數據,並且我想在發布成功后使用導航。 這是示例
export const authLogin = (email, password) => {
const config = {
withCredentials: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': Cookies.get('csrftoken')
}
}
let navigate = useNavigate();
return dispatch => {
console.log('Masuk ke dalam auth file');
dispatch(authStart());
axios.post('/log_in/', {
email: email,
password: password
}, config)
.then(res => {
if (res.data.error) {
alert(res.data.error)
dispatch(authFail(res.data.error))
}
else {
const token = res.data.key;
const expirationDate = new Date(new Date().getTime() + 3600 * 1000);
localStorage.setItem('token', token);
localStorage.setItem('expirationDate', expirationDate);
dispatch(authSuccess(token));
dispatch(checkAuthTimeout(3600));
alert('login berhasil')
navigate("/", { replace: true });
}
})
.catch(err => {
alert(err);
dispatch(authFail(err))
})
}
}
鈎子必須附加到直接附加到 React 組件樹的纖程上。 您不能在組件樹之外使用鈎子,因為 React 無法跟蹤它們(這就是為什么鈎子必須始終以相同的順序運行,並且不能是有條件的,因為 React 在內部跟蹤它們的 state)。
唯一一次可以在組件外部使用鈎子是來自另一個鈎子。
簡而言之,你必須能夠從鈎子調用中畫一條直線返回到 React 渲染組件樹。 如果你不能,那么這是一個無效的鈎子調用。
解決方案
...在您的情況下-只需將navigate
function 作為參數傳遞給您的操作:
const MyComponent = () => {
const navigate = useNavigate();
const doSomethingHandler = () => {
dispatch(authLogin(email,password,navigate))
}
}
const authLogin = (email,password,navigate) => {
// ...do your action and call the `navigate` parameter
// when you need to
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.