gpt4 book ai didi

reactjs - 使用 Promise 中间件为 React-Redux 应用程序添加加载指示器

转载 作者:行者123 更新时间:2023-12-03 14:28:20 24 4
gpt4 key购买 nike

我是 React Redux 新手。我想在用户按下搜索按钮时添加加载文本,并在数据返回或操作完成时关闭文本。在普通的异步函数中,我可以在回调之前和之后切换 isLoading 标志。

但是,在我的应用程序中,我正在调度一个返回“类型”和“有效负载”的操作,这是一个 promise 。然后,中间件 redux-promise 会“自动”转换该 Promise 有效负载并将其发送到 reducer 。换句话说,中间件在幕后为 Promise 执行 .then 操作,并为我的 reducer 提供正确的数据。

在这种情况下,我不确定如何向 View 添加加载文本,因为一旦我调用 this.props.getIdByName(this.state.value),我就不知道数据何时返回。对我来说,合理的位置是在 reducer 内部,因为那是数据返回的时候。但是,我认为这将是一个糟糕的方法,因为 reducer 不应该执行这样的任务?

在我的组件中,我的提交具有以下功能

  handleSubmit(e) {
e.preventDefault();
this.props.getIdByName(this.state.value);
}

在我的 actions/index.js 文件中,我有以下操作生成器

export function getIdByName(name) {
const FIELD = '/characters'
let encodedName = encodeURIComponent(name.trim());
let searchUrl = ROOT_URL + FIELD + '?ts=' + TS + '&apikey=' + PUBLIC_KEY + '&hash=' + HASH + '&name=' + encodedName;
const request = axios.get(searchUrl)

return {
type: GET_ID_BY_NAME,
payload: request
}
}

在我的 reducer /reducers.jsx 中

export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case GET_ID_BY_NAME:
console.log(action.payload.data.data.results[0].id); <-- here the data comes back correctly because reduer called the promise and gave back the data for me
return {...state, id: action.payload.data.data.results[0].id};
default:
return state;
}
}

在我的主 index.js 文件中,我使用以下中间件创建了商店

const createStoreWithMiddleware = applyMiddleware(
promise,
thunk
)(createStore);

最佳答案

当您在使用 redux-promise 时分派(dispatch)以 Promise 作为负载的操作时,redux-promise 中间件将捕获该操作,等待 Promise 解析或拒绝,然后重新分派(dispatch)该操作,现在将 Promise 的结果作为其负载。这意味着您仍然可以处理您的操作,并且一旦您处理它,您就知道它已经完成。所以你是对的, reducer 是处理这个问题的正确地方。

但是,您也认为 reducer 不应该有副作用。他们应该只建立新的国家。那么,答案就是通过在 Redux 中更改应用程序的状态来显示和隐藏加载指示器:)

我们可以向 Redux 存储添加一个名为 isLoading 的标志:

const reducers = {
isLoading(state = false, action) {
switch (action.type) {
case 'START_LOADING':
return true;
case 'GET_ID_BY_NAME':
return false;
default:
return state;
}
},
// ... add the reducers for the rest of your state here
}

export default combineReducers(reducers);

每当您要调用 getIdByName 时,请在调用之前分派(dispatch)类型为 'START_LOADING' 的操作。当 getIdByNameredux-promise 重新分派(dispatch)时,您会知道加载已完成,并且 isLoading 标志将被设置回 false。

现在我们有一个标志来指示我们是否正在 Redux 存储中加载数据。使用该标志,您可以有条件地渲染加载指示器。 :)

关于reactjs - 使用 Promise 中间件为 React-Redux 应用程序添加加载指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43661567/

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