jt2*_*t25 4 reactjs redux react-hooks
我的目的是在内调用一个动作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)
Run Code Online (Sandbox Code Playgroud)
效果很好,但我收到警告
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array react-hooks/exhaustive-deps.
Run Code Online (Sandbox Code Playgroud)
但是,如果要props在我的参数中添加第二个参数,useEffects则它将无限运行。
我在这里的第一个解决方法是使用,useRef但它似乎总是会重新渲染,因此再次重新设置useRef,我认为这在优化方面并不好。
const ref = useRef();
ref.current = props;
console.log(ref)
useEffect(()=>{
ref.current.fetchTodos()
},[])
Run Code Online (Sandbox Code Playgroud)
这里还有其他解决方法吗?
这是eslint警告,如果其中任何依赖项useEffect都不是依赖项数组的一部分。
在您的情况下,您正在props.fetchTodosuseEffect内部使用,并且eslint警告提示您提供props依赖关系,以便在props更改时,useEffect函数将从其关闭处获取更新的props。
但是,因为fetchTodos这不会改变您的应用程序生命周期,并且您只想在可以为您的案例禁用规则后才运行效果。
const ShowTodos = (props) =>{
const { fetchTodos } = props
useEffect(()=>{
fetchTodos()
// eslint-disable-next-line import/no-extraneous-dependencies
},[])
}
const mapStateToProps = (state)=>{
return {
todos:Object.values(state.todos),
currentUserId:state.authenticate.userId
}
}
export default connect(mapStateToProps,{fetchTodos})(ShowTodos)
Run Code Online (Sandbox Code Playgroud)
但是,您可以在不禁用规则的情况下解决问题
const ShowTodos = (props) =>{
const { fetchTodos } = props
useEffect(()=>{
fetchTodos()
},[fetchTodos])
}
Run Code Online (Sandbox Code Playgroud)
但是,我建议您知道什么时候应该完全禁用规则或将值传递给依赖项数组。
| 归档时间: |
|
| 查看次数: |
1389 次 |
| 最近记录: |