今天遇到了钩子问题。我知道也有类似的帖子,并且阅读了使用钩子的规则。现在,当我发布表格时,它给了我这个错误。我知道那是因为我的钩子位于if语句内。但是我怎么弄出来呢?如果它不在函数或语句中,我不知道如何使用此钩子。任何建议将不胜感激。这是代码:
//@version=4
study("Opens +", overlay=true)
higherTF1 = input("D", type=input.resolution)
dailyopen = security(syminfo.tickerid, higherTF1, open)
var line1 = line.new(bar_index, dailyopen,bar_index, dailyopen, xloc=xloc.bar_index, style=line.style_solid,extend=extend.right)
line.set_color(line1, color.black)
line.set_width(line1, 1)
自定义挂钩:
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;
答案 0 :(得分:2)
您可以将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]);
};