我想向社区询问使用 react-redux connect()
和依赖管理在钩子(Hook)中结合现有代码的最佳实践是什么 useEffect()
.
让我们看下面的例子:
/* ... */
const mapStateToProps = (state) => ({
todos: getTodos(state),
currentUserId: getCurrentUserId(state)
})
const mapDispatchToProps = (dispatch) => ({dispatch})
const mapMergeProps = (stateProps, {dispatch}, ownProps) => {
return {
...stateProps,
...dispatchProps,
...ownProps,
fetchTodos: () => dispatch(fetchTodos(stateProps.currentUserId))
}
}
const TodosListContainer = connect(mapStateToProps, mapDispatchToProps, mapMergeProps)
const TodosList = ({todos, fetchTodos, ...props}) => {
const _fetchTodos = useCallback(fetchTodos, [])
useEffect(() => {
_fetchTodos()
}, [_fetchTodos])
return (
<ul>
{todos && todos.map((todo) => <li key={todo.id}>{todo.name}</li>)}
</ul>
)
}
在上面的代码中,useEffect 具有所有的依赖关系,useCallback 确保useEffect 只被触发一次。
然而,这似乎是一个额外的样板层:如果没有 useCallback,作为来自 connect 的 mapMergeToProps
的 props 传递的函数将在每次状态更改时重新创建,并将触发 使用效果
。
我的问题是上面的代码是否正确,在所描述的上下文中是否有更好的方法来处理 useEffect。
最佳答案
我会把它改成下面的
// Leave this one like it is
const mapStateToProps = (state) => ({
todos: getTodos(state),
currentUserId: getCurrentUserId(state)
})
// Map the fetchTodos here
const mapDispatchToProps = {
fetchTodos,
}
// Completely remove the mergeProps
const TodosListContainer = connect(mapStateToProps, mapDispatchToProps)
// Then use the hook like this
const TodosList = ({ todos, fetchTodos, currentUserId, ...props }) => {
useEffect(() => {
fetchTodos(currentUserId)
}, [fetchTodos, currentUserId])
return (
<ul>
{todos && todos.map((todo) => <li key={todo.id}>{todo.name}</li>)}
</ul>
)
}
这不会在每次渲染时触发 useEffect
,因为 Prop 保持不变。它删除了(一些)样板代码。我还认为它可以更容易地理解正在发生的事情,并且它会在 currentUserId
更改时运行效果,这可能是本应发生的事情。
关于reactjs - React Hooks 和 React-Redux 连接 : What is the best practice to make them work together?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57268738/