首页 > 解决方案 > 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>
    )

标签: reactjsreact-hooksuse-effect

解决方案


对于您想要实现的目标,您不需要效果。我会从这样的函数中处理获取:

// simplified the example
const [value, setValue] = useState("initial");

const handleFetch = () => {
  setValue("triggered");
};

return (
  <div>
    <button onClick={handleFetch}>{value}</button>
  </div>
);

推荐阅读