标签: redux-thunk

如何正确使用“next-redux-wrapper”与“Next.js”、“Redux-ToolKit”和 Typescript?

我在 Next.js 应用程序中使用 RTK(redux-toolkit)。我正在尝试在“getInitialProps”内调度 AsyncThunk Action。在搜索时,我发现了一个名为“next-redux-wrapper”的包,它公开了“getInitialProps”内的“store”,但我正在努力弄清楚如何使其与我的项目一起使用。

这是该项目的准系统示例,我目前正在使用带有 2 个减速器的 Typescript。一种减速器使用 AsyncThunk 从 API 获取数据。我已经安装了“next-redux-wrapper”,但我不知道如何实现它,以便所有页面都可以访问“getInitialProps”内的“store”。该包的文档有一个示例,但相当令人困惑。

这是我的 store.ts 的样子......

import { Action, configureStore, ThunkAction } from '@reduxjs/toolkit';
import { createWrapper, HYDRATE } from 'next-redux-wrapper';
import { counterReducer } from '../features/counter';
import { kanyeReducer } from '../features/kanye';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
    kanyeQuote: kanyeReducer,
  },
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string> …
Run Code Online (Sandbox Code Playgroud)

typescript redux redux-thunk next.js redux-toolkit

9
推荐指数
1
解决办法
3万
查看次数

在react + redux中预加载组件数据的正确方法

我不知道从API预加载数据以供组件使用的正确方法.

我编写了一个无状态组件,它应该呈现数据:

import React, { PropTypes } from 'react';

const DepartmentsList = ({ departments }) => {
  const listItems = departments.map((department) => (
    <li><a href="./{department}">{department.title}</a></li>
  ));
  return (
    <ul>
      {listItems}
    </ul>
  );
};

DepartmentsList.propTypes = {
  departments: PropTypes.array.isRequired
};

export default DepartmentsList;
Run Code Online (Sandbox Code Playgroud)

我有一个动作可以从API中检索数据:

import { getDepartments } from '../api/timetable';

export const REQUEST_DEPARTMENTS = 'REQUEST_DEPARTMENTS';
export const RECEIVE_DEPARTMENTS = 'RECEIVE_DEPARTMENTS';

const requestDepartments = () => ({ type: REQUEST_DEPARTMENTS });
const receiveDepartments = (departments) => ({ type: RECEIVE_DEPARTMENTS, departments });

export function …
Run Code Online (Sandbox Code Playgroud)

reactjs redux redux-thunk

8
推荐指数
1
解决办法
5167
查看次数

ReactJS + Redux:为什么即使使用正确的API请求,MongoDB也不会将数据保存到数据库中?

我在ReactJS + Redux项目中设置了MongoDB/Webpack/NodeJS Express.

我正在从redux中的动作创建者那里进行API调用,并且到达API服务器并获得成功的状态,但数据永远不会被保存,即使在终端中检查也不会创建数据库,mongo -> dbs并且它不显示practicedb我命名的数据库它作为.

可能是什么问题?我错过了什么吗?

任何指导或见解将不胜感激.谢谢

这是我为API设置的:

import axios from 'axios';
import { browserHistory } from 'react-router';
import cookie from 'react-cookie';
import { AUTH_USER, AUTH_ERROR } from './types';

const API_URL = 'http://localhost:3000/api';

export function errorHandler(dispatch, error, type) {
  let errorMessage = (error.data.error) ? error.data.error : error.data;

   // NOT AUTHENTICATED ERROR
   if(error.status === 401) {
     errorMessage = 'You are not authorized to do this.';
   }

  dispatch({
    type: type,
    payload: errorMessage
  });
}

export function …
Run Code Online (Sandbox Code Playgroud)

javascript mongodb node.js reactjs redux-thunk

8
推荐指数
1
解决办法
973
查看次数

为什么要使用Redux Thunk

为什么使用Redux Thunk然后可以做这样的事情:

ReadableAPI.getCategories().then((categories)=>{
      console.log('after getCategories', categories)

      this.props.dispatch(addCategories(categories))
    })
Run Code Online (Sandbox Code Playgroud)

这不是更直接,并实现同样的事情?

reactjs redux-thunk react-redux

8
推荐指数
1
解决办法
908
查看次数

使用connect时使用redux-thunk键入错误

我正在使用redux和redux-thunk与typescript.我试图通过connect()注入一个组件,一个简单的thunk动作创建者,使用mapDispatchToProps.

操作

export enum TestActionTypes {
  THUNK_ACTION = "THUNK_ACTION"
}

export interface ThunkAction {
  type: TestActionTypes.THUNK_ACTION;
}

export type TestAction = ThunkAction;
Run Code Online (Sandbox Code Playgroud)

动作创作者

export function thunkActionCreator() {
  return function(dispatch: Dispatch<any>) {
    dispatch({ type: TestAction.THUNK_ACTION });
  };
Run Code Online (Sandbox Code Playgroud)

连接组件

interface DemoScreenState {}

interface OwnProps {}

interface StateProps {}

interface DispatchProps {
  testThunk: () => void;
}

type DemoScreenProps = StateProps & DispatchProps & OwnProps;

class DemoScreen extends React.Component<
  DemoScreenProps,
  DemoScreenState
> {
  constructor(props: DemoScreenProps) {
    super(props);
  }

  componentDidMount() {
    this.props.testThunk();
  }

  render() …
Run Code Online (Sandbox Code Playgroud)

typescript redux redux-thunk react-redux

8
推荐指数
1
解决办法
2986
查看次数

模拟api in react redux-thunk项目返回undefined

我在redux世界中相当新,还没有一个项目构建鸭子的方式.我试图理解它并使用它来制作一个模拟api,因为我还没有准备好后端.我正在使用遗留代码,我想弄清楚.有一个名为data的文件夹,它有一个duck和一个backendApi文件.Duck文件看起来像这样.

数据/ duck.jsx

import { createSelector } from 'reselect';
import { createReduxApi } from './backendApi';

const getDataContext = state => state.default.dataContext;

const backendReduxApi = createBackendReduxApi(getDataContext);

// Action creators
export const makeRestApiRequest = endpointName => backendReduxApi .makeRequestActionCreator(endpointName);

export const resetRestApi = endpointName => backendReduxApi .makeResetActionCreator(endpointName);

// Reducers
export const dataReducer = backendReduxApi .createReducer();

// Selectors
const getRestApiState = endpointName => backendReduxApi .getEndpointState(endpointName);
export const getRestApiData = endpointName => createSelector([getRestApiState(endpointName)], apiState => apiState.data);
export const getRestApiMeta …
Run Code Online (Sandbox Code Playgroud)

ajax reactjs redux redux-thunk

8
推荐指数
1
解决办法
277
查看次数

用于thunk调度的正确TypeScript类型?

我有一个异步redux动作,所以使用thunk中间件.

我有mapStateToProps,mapDispatchToPropsconnect为组件的功能如下:

const mapStateToProps = (store: IApplicationState) => {
  return {
    loading: store.products.loading,
    products: store.products.products
  };
};
const mapDispatchToProps = (dispatch: any) => {
  return {
    getAllProducts: () => dispatch(getAllProducts())
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ProductsPage);
Run Code Online (Sandbox Code Playgroud)

这一切都有效,但我想知道是否有可能替换anydispatch参数中的类型mapDispatchToProps

我试过ThunkDispatch<IApplicationState, void, Action>但在connect函数上遇到以下TypeScript错误:

Argument of type 'typeof ProductsPage' is not assignable to parameter of type 'ComponentType<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>>'. …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs redux redux-thunk

8
推荐指数
2
解决办法
910
查看次数

如何在 React.js 应用程序中刷新 JWT 令牌?

我在这里检查了所有类似的问题,但没有一个是我需要的。我正在保护我的应用程序中的路由,并随每个请求发送 JWT,这里一切正常。问题是当 JWT 到期时,我需要知道如何刷新该令牌并使用户保持登录状态,而不是注销用户。

每个人都在谈论创建一个处理它的“中间件”,但没有人说如何创建该中间件以及其中有什么?

那么,这样做的最佳实践是什么?我应该在发送任何请求之前检查 JWT 的到期日期吗?或者我应该等待“401”响应然后尝试刷新令牌(我不知道该怎么做),或者究竟是什么?

如果有人在 Github 上有这样的中间件或包或项目的工作示例可以帮助我解决这个问题,那就太好了。

我只对流程的前端部分感兴趣,从反应发送什么以及我应该收到什么以及如何处理它。

jwt reactjs redux-thunk react-redux axios

8
推荐指数
1
解决办法
1万
查看次数

使用 React 18 StrictMode 对 useEffect 进行不需要的 thunk 双重调度

我试图在页面的第一次渲染和按钮单击时调度一个重击。这是它的示例代码:

export default function App() {
  const [loading, setLoading] = useState(false);
  const [finished, setFinished] = useState(false);
  const count = useSelector(countSelector);
  const dispatch = useDispatch();

  const appendCounter = useCallback(() => {
    if (!loading) {
      setLoading(true);
      setFinished(false);

      dispatch(thunk()).finally(() => {
        setLoading(false);
        setFinished(true);
      });
    }
  }, [loading, dispatch]);

  useEffect(() => {
    if (!loading && !finished) {
      appendCounter();
    }
  }, [appendCounter, loading, finished]);

  return (
    <div className="App">
      {!loading && finished ? (
        <>
          <h2>{count}</h2>
          <button onClick={appendCounter}>Append</button>
        </>
      ) : (
        <h2>loading</h2>
      )}
    </div>
  ); …
Run Code Online (Sandbox Code Playgroud)

reactjs redux redux-thunk react-redux react-hooks

8
推荐指数
0
解决办法
1214
查看次数

如何使用 react-redux 存储令牌并在多个 axios 请求上使用它?

我正在使用 react native 构建一个应用程序,它要求我get request使用令牌在同一个 API 上执行多个操作。

假设网址是这样的

令牌 URL = https://test.co/v1/tokens、API URL 1 =https://test.co/v1/students和 API URL 2 =https://test.co/v1/cars

首先,为了从任一 API URL 获取数据,我是这样写的

示例 students_actions.js

import axios from 'axios';
import { FETCH_STUDENT } from './types';

const TOKEN_URL = '...'
const STUDENT_URL = '...'

export const fetchStudent = (callback) => async (dispatch) => {
    axios.post(TOKEN_URL, {
        email: 'email',
        password: 'password',
        role: 'user'
    })
    .then((response) => {
        const accessToken = response.data.token;
        //console.log(accessToken);
        axios.get(STUDENT_URL, {
            headers: { …
Run Code Online (Sandbox Code Playgroud)

javascript api react-native redux-thunk react-redux

7
推荐指数
1
解决办法
7487
查看次数