gpt4 book ai didi

reactjs - 使用 redux saga 获取数据

转载 作者:行者123 更新时间:2023-12-05 03:56:35 24 4
gpt4 key购买 nike

我创建了一个示例,用于从我使用 redux-thunk 的 API 获取数据。以下代码正在运行。

在这种情况下,我想重写我的代码,但使用 redux saga

import React from 'react';
import {createStore, applyMiddleware} from 'redux';
import ReactDOM from "react-dom";
import thunk from 'redux-thunk';
import axios from 'axios';

function App(props) {
const initialState = {
loading: false,
data: [],
error: ''
};
const reducer = function (state = initialState, action) {
switch (action.type) {
case 'START_FETCH':
return {
...state,
loading: true
};
case 'PROCESS_FETCH':
return {
...state,
loading: false,
data: action.payload,
error: ""
};
case 'END_FETCH':
return {
...state,
loading: false,
data: [],
error: action.payload
}
}

return state;
};
const START_FETCH = 'START_FETCH';
const PROCESS_FETCH = 'PROCESS_FETCH';
const END_FETCH = 'END_FETCH';
let startFetchFun = () => {
return {
type: START_FETCH,
loading: true
}
};

let processFetchFun = (users) => {
return {
type: PROCESS_FETCH,
payload: users
}
};

let endFetchFun = (error) => {
return {
type: PROCESS_FETCH,
payload: error
}
};

let fetchUsersWithThunk = () => {
return function (dispatch) {
dispatch(startFetchFun());
axios.get('https://jsonplaceholder.typicode.com/users')
.then((response) => {
dispatch(processFetchFun(response.data));
})
.catch((error) => {
dispatch(endFetchFun(error.message));
console.log(error.message);
})
}
};

const store = createStore(reducer, applyMiddleware(thunk));
store.subscribe(() => {
console.log(store.getState())
});
store.dispatch(fetchUsersWithThunk());


return (
<div className="main">
<h1>Redux-Thunk</h1>
</div>
);
}

ReactDOM.render(
<App/>, document.getElementById('root'));

我想使用 redux saga 编写上面的代码,以更好地理解 sagas。那么,如何在这个例子中使用 redux-saga 呢?谁能帮助我?

最佳答案

Redux Saga 使用 yield call 像 api 服务一样调用 promises,并使用 yield put 将操作分派(dispatch)到商店。

区别在于阻止和不阻止调用。因为我们要等待服务器响应我们的请求,所以我们将使用 yield call 这是一个阻塞函数。使用 yield put({ type: "actionName"}) 而不是直接在生成器 saga 中调度操作。这对于测试目的也很有用。

所以你应该把你的传奇写成如下:

import {all, fork, put, call, takeLatest} from 'redux-saga/effects';

function* handleRequest (action) {
try {
yield put(startFetchFunc()); // dispatch the action to the store.
const result = yiels call(apiService.users, [data to pass]); // wait for the response blocking the code execution.
yield put(processFetchFun(result)); // dispatch the action to the store containing the data
} catch (e) {
yield put(endFetchFun('Error'));
}
}

function* watchRequest() {
yield takeLatest({type: "START_FETCH"}, handleRequest);
}

export function* rootSaga() {
yield all([
fork(wathcRequest),
// ... more watchers will be here...
]);
}

按照此处的说明配置您的存储 https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html

我建议你多读一遍文档。它包含许多有用的信息,这些信息起初可能会很奇怪,但一旦您理解了它的工作原理就会清楚得多。

关于reactjs - 使用 redux saga 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59244564/

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