reactjs - 为什么它一直告诉我有一个循环错误?
问题描述
错误:超过最大更新深度。当组件在 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>
)
解决方案
我认为这里的问题是只有在使用钩子dispatch
更改输入值时才应该调用它。useEffect
由于它位于组件内部,因此每次重新渲染组件时都会调用它。
useEffect(() => {
dispatch({
type: actionTypes.SET_SEARCH_TERM,
term: input
});
}, [input]);
推荐阅读
- jquery - 通过 jQuery EACH 循环添加多个 WooCommerce 产品
- php - 我如何在 PHP 中使用动态变量
- node.js - Mongodb:仅FindOne那些与mongodb中的条件匹配的数组对象
- angular - 如何修复angular2-signaturePad中的“无法读取未定义的属性'toDataURL'”
- django - modelchoicefield 显示没有名称的对象 1 和对象 2 的问题?
- python - 如何使多线程我的树莓派之间的通信代码?
- php - wordpress 帖子无法在自定义模板上检索
- angular - 嵌套的 http 调用不适用于 ForkJoin
- excel - 在同一行中选择列表项后,如何确定单元格的颜色?
- javascript - 离线时如何使用 Sentry 记录错误?