reactjs - useEffect 在组件加载时触发,而不是在状态更改时触发,正如我设置的那样
问题描述
我试图在我更改时触发我的 useEffect useState
,但是,它只在组件加载时触发一次(我根本不想要) 代码有什么问题?
const [value, setValue] = useState('initial');
useEffect(()=>{
let url = "https://hacker-news.firebaseio.com/v0/topstories.json";
let count = 30;
axios({
method: 'post',
url: '/api/grabIt',
data: {
url: url,
count: count
}
})
.then(function (res) {
console.log(res.data.response)
})
.catch(function (error) {
console.log(error)
});
},[value]);
return (
<div className={styles.displayType}>
<ButtonContainer/>
<Button buttonColor={!!isDarkMode}
onClick={ () => setValue('triggered')}
>FETCH</Button>
</div>
)
解决方案
对于您想要实现的目标,您不需要效果。我会从这样的函数中处理获取:
// simplified the example
const [value, setValue] = useState("initial");
const handleFetch = () => {
setValue("triggered");
};
return (
<div>
<button onClick={handleFetch}>{value}</button>
</div>
);
推荐阅读
- sql - 如何根据 column2 中的字符串更新 column1?
- visual-studio - 安装自定义生成文件的 CMake 语法
- c - 在哪里读取 cmd 输入,如“myapp.exe 输入”或“myapp.exe -?” (我使用cmd)
- django - 是否有一些相当于 {% url 'some-name' %} 的 router.register(...)
- java - 带有 VarArgs 的方法首先从 JSP 调用
- angular - ngrx:在自定义对话框中等待确认或取消
- symfony - VS Code 自动完成 Symfony 不起作用
- .net - Babelfor 不能很好地混淆 winform “fieldName”?
- python - 使用 Python 包发布 C 或 Fortran 代码段的最简单方法
- java - 我正在尝试通过使用 java 8 流遍历嵌入列表来返回数据