我都赞成不解决您没有的问题。
所以我开始学习和使用React而没有Redux。
但是现在我的应用程序状态已经增长,我开始遇到一些状态管理问题。
越来越难以处理,我的App.js
充满了<SomeContext.Provider's>
。
所以我现在愿意将Redux添加到我的应用程序中。
但是,当然,我要进行很多API调用以获取我的应用状态的数据。因此,从我的研究中,我基本上有[[用于异步状态更新的两个主要选项: redux-thunk
和redux-saga
。
但是我的问题是:我真的需要它们(thunk或saga)吗?
我制作了似乎可行的代码,并使用异步数据更新了商店。结果:
https://codesandbox.io/s/ecstatic-antonelli-9cu7m
代码:
基本上我有这个减速器:getApiDataReducer.js
const initialState = {
loading: false,
error: null,
data: null
};
function getApiDataReducer(state = initialState, action) {
switch (action.type) {
case "GET_DATA_START":
return {
...initialState,
loading: true
};
case "GET_DATA_SUCCESS":
return {
...initialState,
loading: false,
data: action.payload
};
case "GET_DATA_FAIL":
return {
...initialState,
loading: false,
error: action.payload
};
default:
return state;
}
}
export default getApiDataReducer;
rootReducer.js
import getApiDataReducer from "./getApiDataReducer";
import { combineReducers } from "redux";
const rootReducer = combineReducers({
getApiData: getApiDataReducer
});
export default rootReducer;
而且我的App组件中有index.js文件:
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider, useSelector, useDispatch } from "react-redux";
import rootReducer from "./reducers/rootReducer";
import "./styles.css";
const store = createStore(rootReducer);
function mockAPIcall() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("DATA FROM API"), 1000);
});
}
function mockAPIcallError() {
return new Promise((resolve, reject) => {
setTimeout(() => reject("SOMETHING WRONG HAPPENED"), 1000);
});
}
function App() {
const { loading, error, data } = useSelector(state => state.getApiData);
const dispatch = useDispatch();
async function getAsyncData() {
dispatch({ type: "GET_DATA_START" });
try {
const newData = await mockAPIcall();
dispatch({ type: "GET_DATA_SUCCESS", payload: newData });
} catch (err) {
dispatch({ type: "GET_DATA_FAIL", payload: err });
}
}
async function getAsyncDataError() {
dispatch({ type: "GET_DATA_START" });
try {
const newData = await mockAPIcallError();
dispatch({ type: "GET_DATA_SUCCESS", payload: newData });
} catch (err) {
dispatch({ type: "GET_DATA_FAIL", payload: err });
}
}
return (
<div>
<div>
Data:
{
loading ? "Loading..."
: error ? error
: data ? data
: "No data yet..."
}
</div>
<button onClick={getAsyncData}>Get Async Data</button>
<button onClick={getAsyncDataError}>Get Async Error</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
我很确定那些库(问题:
redux-thunk
和redux-saga
)可以做的更多。因此,通过采用这种简单得多的模式,我想知道这些库的哪些关键功能正在丢失
。由于到目前为止我在应用程序上所做的工作,我几乎可以将所有内容重构为这种模式。但是我很确定我将通过这种方式关闭将来的大门。这似乎是一个开放式问题,但我认为不是。
人们使用这些库,并且他们应该能够确定使用此模式时未考虑哪些重要功能。
我都赞成不解决您没有的问题。所以我开始学习和使用没有Redux的React。但是现在我的应用程序状态已经增长,我开始面临一些状态管理问题。 ...