【发布时间】:2019-09-18 18:23:50
【问题描述】:
我的目标是在 useEffect 中调用一个动作。
const ShowTodos = (props) =>{
useEffect(()=>{
props.fetchTodos()
},[])
}
const mapStateToProps = (state)=>{
return {
todos:Object.values(state.todos),
currentUserId:state.authenticate.userId
}
}
export default connect(mapStateToProps,{fetchTodos})(ShowTodos)
它工作正常,但我收到了警告
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array react-hooks/exhaustive-deps.
但如果我要在useEffects 中添加props 作为我的第二个参数,那么它将无休止地运行。
我在这里的第一个解决方法是使用useRef,但它似乎总是会重新渲染,因此再次重新设置我认为在优化方面不好的 useRef。
const ref = useRef();
ref.current = props;
console.log(ref)
useEffect(()=>{
ref.current.fetchTodos()
},[])
这里还有其他解决方法吗?
【问题讨论】:
-
Dan Abramov 在overreacted.io/a-complete-guide-to-useeffect 对此案也有深入的解释。值得一读。
标签: reactjs redux react-hooks