pra*_*esh 4 reactjs redux react-hooks
我正在学习redux钩子,想知道如何将其与redux saga一起使用。
目前,用传奇编写的代码如下。
centres.js
componentDidMount() {
this.props.getCenters();
}
...
<tbody>
{
this.props.centers ?
<React.Fragment>
{
centers.map((center, index) =>
<tr key={index}>
<td>{center.name}</td>
<td>{center.zip}</td>
</tr>
)
}
</React.Fragment>
:
<tr>
<td> No data available</td>
</tr>
}
</tbody>
Run Code Online (Sandbox Code Playgroud)
动作文件定义如下。
export const getCenters = () => ({
type: types.CENTERS_REQUEST,
});
Run Code Online (Sandbox Code Playgroud)
saga文件的定义如下。
import { DEFAULT_ERROR_MSG } from '../../constants';
import { instance as centerProvider } from '../services/centerProvider';
function* fetchCenters() {
try {
const response = yield call(centerProvider.getCenters);
const centers = response.data.data.centers;
// dispatch a success action to the store
yield put({ type: types.CENTERS_SUCCESS, centers});
} catch (error) {
// dispatch a failure action to the store with the error
yield put(DEFAULT_ERROR_MSG);
}
}
export function* watchCenterRequest() {
yield takeLatest(types.CENTERS_REQUEST, fetchCenters);
}
export default function* centerSaga() {
yield all([
watchCenterRequest()
]);
}
Run Code Online (Sandbox Code Playgroud)
所以问题是
如果需要,可以使用useReducer钩子代替redux。但是,如果您在嵌套在DOM树的不同分支中的不同组件之间具有共享状态,则实现useReducer可能会有些复杂。因此,使用redux和saga与钩子并不矛盾。如果比类组件更喜欢功能组件,则只需要钩子即可。
您可以Centers像这样将类组件重新构造为功能组件:
function Centers(props) {
useEffect(() => {
props.getCenters();
}, []);
return (
//render what you need here
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3615 次 |
| 最近记录: |