我已经开始在功能组件中使用 redux-toolkit 切片器,(示例来自 react-redux 示例)
切片器:
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: state => {
state.value += 1;
},
decrement: state => {
state.value -= 1;
},
incrementByAmount: (state, action) => {
state.value += action.payload;
},
},
});
在组件中使用:
const count = useSelector(selectCount);
const dispatch = useDispatch();
return (
<button
className={styles.button}
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
)
我的问题是如何在类组件中使用这个切片器,因为我不能在它们内部使用钩子。 我试过使用 connect(来自 redux),但我找不到一种方法将切片器的动作和选择器“缝合”到我的组件。 我也找不到任何关于此的文档。
答案 0 :(得分:11)
类与函数组件以及 redux-toolkit 与“vanilla”redux 是两个独立的决定,彼此之间没有任何影响。 (不过你应该知道,对于 React 的一切,推荐函数组件和钩子而不是类组件)。
<块引用>我尝试过使用 connect(来自 redux),但我找不到将操作和选择器从切片器“缝合”到我的组件的方法。
在使用 useDispatch
和 useSelector
时,文档如何“拼接”操作和选择器?这样做,但使用 connect
高阶组件。
您发布的文档示例中的 increment()
函数不仅神奇地存在,还需要从切片中导入。您可以导出整个 actions
对象并使用 actions.increment
,但您通常会看到导出为单个变量的操作。
来自the docs:
<块引用>大多数情况下,您可能希望使用 ES6 解构语法将动作创建器函数提取为变量,也可能需要使用 reducer:
您的切片文件可能如下所示:
const counterSlice = createSlice( /* same as before */ );
// destructure actions and reducer from the slice (or you can access as counterSlice.actions)
const { actions, reducer } = counterSlice;
// export individual action creator functions
export const { increment, decrement, incrementByAmount } = actions;
// often the reducer is a default export, but that doesn't matter
export default reducer;
connect
的第一个参数是 mapStateToProps
,您可以在其中使用选择器(内联箭头函数 state => state.something
或您导入的选择器函数)从状态创建道具对象。这可能看起来像:
const mapStateToProps = (state) => ({
count: state.counter.value
});
第二个参数 mapDispatchToProps
是可选的。如果您向动作创建者传递一个对象,您的组件将收到那些已经绑定到 dispatch
的动作创建者的版本。您可以直接调用 this.props.increment()
而不是 this.props.dispatch(increment())
。您将在带有 connect
的教程中看到这种常用的语法。
import React from "react";
import { connect } from "react-redux";
import { increment, decrement } from "./counterSlice";
class MyComponent extends React.Component {
render() {
return (
<div>
<h1>Count is {this.props.count}</h1>
<button onClick={() => this.props.increment()}>
Increment
</button>
<button onClick={() => this.props.decrement()}>
Decrement
</button>
</div>
);
}
}
const mapStateToProps = (state) => ({
count: state.counter.value
});
const mapDispatchToProps = { increment, decrement };
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
如果您完全不使用 mapDispatchToProps
参数,您的组件将接收原始 dispatch
函数。您可以对导入的动作创建者(如 this.props.dispatch(increment())
)调用调度。此语法更类似于 useDispatch
的使用方式。 connect
和 useDispatch
都允许您访问 dispatch
函数,并且您可以使用从操作创建器函数(如 increment()
或 {{1})创建的操作调用该函数}}。
decrement()