今天遇到了钩子的问题。 我知道有一个类似的帖子,我阅读了使用钩子的规则。 现在,当我发布表格时,它给了我这个错误。 我知道这是因为我的钩子在 if 语句内。 但是我怎样才能把它拿出来呢?我不知道如果它不在函数或语句中,如何使用这个钩子。 任何建议将不胜感激。 这是代码:
import React, { FunctionComponent, useState, useEffect } from 'react';
import usePost from '../hooks/usepost'
import Article from './article';
interface ArticlePosted {
title: string,
body: string,
author: string
}
const Post: FunctionComponent = () => {
const [details, detailsReady] = useState({})
const postArticle = (e) => {
e.preventDefault()
const postDetails = {
title: e.target.title.value,
body: e.target.body.value,
author: e.target.author.value
}
detailsReady(postDetails)
}
if (Object.keys(details).length !== 0) {
console.log(details)
usePost('http://localhost:4000/kb/add', details)
}
return (
<div>
<form onSubmit={postArticle}>
<p>
Title <input type='text' name='title' />
</p>
<p>
Body <textarea name='body' rows={4} />
</p>
<p>
Author <input type='text' name='author' />
</p>
<button type='submit'>Submit Article</button>
</form>
</div>
);
};
export default Post;
自定义钩子:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const usePost = (url, postDetails) => {
//set empty object as data
console.log(url, "DFLSKDJFSDLKFJDLKJFDLFJ")
console.log(postDetails)
useEffect(() => {
console.log('usePost running')
axios.post(url, postDetails)
.then(res => {
console.log(res)
return
})
}
, [postDetails]);
};
export default usePost
您可以将if 语句逻辑移动到usePost
钩子中。
const usePost = (url, postDetails) => {
useEffect(() => {
if (Object.keys(postDetails).length === 0){
return console.log('Not posting'); // Don't post anything if no details
}
// Otherwise, post away
console.log('usePost running')
axios.post(url, postDetails)
.then(res => {
console.log(res)
return
})
}
, [postDetails]);
};