gpt4 book ai didi

javascript - 创建 Redux-saga 监听器

转载 作者:行者123 更新时间:2023-12-01 01:24:16 26 4
gpt4 key购买 nike

我对 redux saga 有一个 UPDATE_DATE 操作。我想在每次修改日期时更新多个资源。我想实现一个监听器来触发回调的 UPDATE_DATE_SUCCESS 操作。任何想法?如果我可以从 React 组件中调用它,那就太好了。

行动: 更新日期 UPDATE_DATE_SUCCESS UPDATE_DATE_FAILURE

export const {
updateDate,
OnDateChange,
} = createActions({
[ActionTypes.UPDATE_DATE]: (date) => date,
});

传奇

export function* updateDate(newDate) {
console.log('from sagas to reducer', newDate); // eslint-disable-line no-console
try {
yield put({
type: ActionTypes.UPDATE_DATE_SUCCESS,
payload: newDate,
});
} catch (err) {
/* istanbul ignore next */
yield put({
type: ActionTypes.UPDATE_DATE_FAILURE,
payload: err,
});
}
}

export default function* root() {
yield all([
takeLatest(ActionTypes.UPDATE_DATE, updateDate),
takeEvery(ActionTypes.UPDATE_DATE_SUCCESS, test),
]);
}

React 组件的理想实现

  componentDidMount() {
const { dispatch } = this.props;

dispatch(onDateChange((newDate) => {
dispatch(getApps(newDate));
dispatch(getPlatforms(newDate));
dispatch(getNetworks(newDate));
dispatch(getCountries(newDate));
dispatch(getFormats(newDate));
dispatch(getDevices(newDate));
dispatch(getNetworkKeys(newDate));
}));
}

有什么帮助吗?谢谢!

最佳答案

Redux Sagas 背后的想法是处理 Saga 上而不是组件中的操作/事件的副作用。我认为这样做的方法是这样的(注意片段代码未经测试,仅将其用作引用/示例):

// --> Saga <-- //
import { getApps, getPlatforms, getNetworks, getCountries, getFormats, getDevices, getNetworkKeys } from './actions.js';

export function* updateDateWatcher(action) {
const { payload: newDate } = action;
if (!newDate) return;

try {
// dispatch all required actions
yield all([
put(getApps(newDate),
put(getPlatforms(newDate),
put(getNetworks(newDate)),
put(getCountries(newDate)),
put(getFormats(newDate)),
put(getDevices(newDate)),
put(getNetworkKeys(newDate)),
]);
// then trigger a success action if you want to
yield put(updateDataSuccess());
} catch (err) {
// if something wrong happens in the try this will trigger
yield put(updateDateFailure(err));
}
}

export default function* root() {
yield all([
takeLatest(ActionTypes.UPDATE_DATE, updateDateWatcher),
]);
}


// --> Component <-- //
import { updateDate } from './actions.js';

class MyComponent extends Component {
componentDidMount() {
const { onDateChange } = this.props;
const date = new Date();
onDateChange(date); // -> triggers ActionTypes.UPDATE_DATE
}
}

const mapDispatchToProps = dispatch => ({
onDateChange: (newDate) => dispatch(updateDate(newDate)),
});

export default connect(null, mapDispatchToProps)(MyComponent);

关于javascript - 创建 Redux-saga 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com