首页 > 解决方案 > 为什么它一直告诉我有一个循环错误?

问题描述

错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制了嵌套更新的数量以防止无限循环。

我正在做一个谷歌搜索栏克隆并制作 ReactJS 上下文 API,然后到了这个我停下来的地方,不能去更多 cz 不知道如何修复它。我的代码中没有看到无限循环,有人可以帮忙吗?

function Search({hideButtons = false}) {
const [{}, dispatch] = useStateValue();

const [input, setInput] = useState('');
const history = useHistory();


const search = e => {
    e.preventDefault();
    history.push('/search');
};

dispatch({
    type: actionTypes.SET_SEARCH_TERM,    //<<<<<<<< Here where is tell me got the error
    term: input
});


return (
    <form className='search'>
        <div className='search__input'>
            <SearchIcon className='search__inputIcon' />
            <input value={input} onChange={e => setInput(e.target.value)} />
            <MicIcon />
        </div>

        {!hideButtons ? (
            <div className='search__buttons'>
                <Button type='submit' onClick={search} variant='outlined'>Google Search</Button>
                <Button variant='outlined'>I'm Feeling Lucky</Button>
            </div>
        ) : (
            <div className='search__buttons'>
                <Button className='search__hideButtons' type='submit' onClick={search} variant='outlined'>Google Search</Button>
                <Button className='search__hideButtons' variant='outlined'>I'm Feeling Lucky</Button>
            </div>
        )}

    </form>
)

标签: reactjs

解决方案


我认为这里的问题是只有在使用钩子dispatch更改输入值时才应该调用它。useEffect由于它位于组件内部,因此每次重新渲染组件时都会调用它。

useEffect(() => {
    dispatch({
       type: actionTypes.SET_SEARCH_TERM, 
       term: input
    });
}, [input]);

推荐阅读