react-redux 的非常基本的简单 GET 示例
我有一个“MockAPI”,它模拟对 API 的 GET 请求,如下所示:
const dashboards = [
{
"Id":1,
"title":"Overview"
},
{
"Id":2,
"title":"Overview"
},
{
"Id":3,
"title":"Overview"
},
{
"Id":4,
"title":"Overview"
}
];
class DashboardApi {
static getAllDashboards() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Object.assign([], dashboards));
}, delay);
});
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试在 react-redux 流程中开发,通过单击按钮来调度操作,然后通过 redux 存储更新组件。
这是我的组件代码:
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import * as dashboardActions from '../../actions/dashboardActions';
class HomePage extends React.Component …Run Code Online (Sandbox Code Playgroud) 我正在为我的应用程序创建一个通用的模态 React 组件来显示各种不同的东西。我希望它足够灵活以显示纯 HTML 和交互式 React 组件。
我已经通过将可显示组件存储在我的 Redux 模态减速器中来使其工作。到目前为止,我还没有遇到任何问题。
以前有没有人采用过这种方法?我无法在网上找到任何示例,所以我不确定这是否是不好的做法。如果是这样,您是否建议使用另一种方法来处理?
初始状态如下所示:
const INITIAL_STATE = {
myArray: []
};
Run Code Online (Sandbox Code Playgroud)
现在在我的减速器中,我想将一个新对象附加到现有数组中。我想出了这样的东西,但它没有按预期工作。
case ADD_TO_ARRAY:
return {
...state,
myArray: [...state[ { action.payload.key: action.payload.value} ]]
};
Run Code Online (Sandbox Code Playgroud)
注意:我想使用在操作有效负载中传递的键和值来创建一个新对象。
有人成功地将 Redux Offline 与 RTK Query 结合起来吗?
我不确定如何使用离线元数据装饰 RTK 查询突变,如 RTK 查询文档中所述:
const registerUser = (name, email) => ({
type: 'REGISTER_USER',
payload: { name, email },
meta: {
offline: {
// the network action to execute:
effect: { url: '/api/register', method: 'POST', body: `name=${name}&email=${email}`, headers: { 'content-type': 'application/x-www-form-urlencoded' } },
// action to dispatch when effect succeeds:
commit: { type: 'REGISTER_USER_COMMIT', meta: { name, email } },
// action to dispatch if network action fails permanently:
rollback: { type: 'REGISTER_USER_ROLLBACK', …Run Code Online (Sandbox Code Playgroud) 在很长一段时间没有接触 React 之后,我现在重新开始使用 React,我正在查看我之前使用过的 redux 工具包,我看到了 RTK 查询。
我试图理解它,并且认为我已经理解了,但是有一件事我不确定是我遗漏了还是它只是被设计成这样工作的。
我们是否只使用 RTKQ 来获取根本不需要缓存的数据?例如加载用户点击的特定帖子?我这么问是因为在我看过或读过的任何教程中我都没有看到与其他切片的任何交互。
例如,如果我需要获取一些需要保留的信息(否则我只会继续获取它),那么我将使用常规createAsyncThunk?
正如标题所说。这对我来说非常奇怪。
我非常清楚地从categoriesApi.js调用getThisCategory(genre)查询,它应该是:
'https://kitsu.io/api/edge/anime?filter%5Bcategories%5D=${genre}'
但在我的控制台中出现错误:
“获取https://kitsu.io/api/edge/Vampire/anime?limit=20 404”。
在我看来,这就像来自animeApi.js 文件的查询,传入了类型参数。我不知道为什么它要调用这个查询。
请有人帮忙,这真的很令人沮丧。
文件如下:
AnimeApi.js(不应该被调用的查询,但确实是):
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const animeApiHeaders = {
"Accept": "application/vnd.api+json",
"Content-Type": "application/vnd.api+json",
};
const baseUrl = 'https://kitsu.io/api/edge';
const createRequest = (url) => ({ url, headers: animeApiHeaders });
export const animeApi = createApi({
reducerPath: 'animeApi',
baseQuery: fetchBaseQuery({ baseUrl }),
endpoints: (builder) => ({
getCategoryOfAnime: builder.query({
query: (category) =>
createRequest(`/${category}/anime?limit=20`)
}),
})
});
export const { useGetCategoryOfAnimeQuery } = animeApi;Run Code Online (Sandbox Code Playgroud)
categoriesApi.js(应该调用的查询):
import { createApi, fetchBaseQuery } from …Run Code Online (Sandbox Code Playgroud)我一直通过使用 React 和 Redux 创建任务管理器应用程序来学习 Typescript。我试图将我的状态作为字典数组发送到 Redux,但问题是我需要声明一个空字典数组,然后才能通过它发送我的状态。
这是我的App.tsx文件:
import React, { FC, useState } from "react"
import { useSelector, useDispatch } from "react-redux"
import TodoList from "./Components/TodoList"
import NameTodo from "./Components/NameTodo"
import { RootState } from "./todoStore"
import { createTodoCard } from "./todoReducer"
interface TodoListTemplate {
title: string,
id: number,
}
const App: FC = () => {
// Contains all the generated todo-lists
const [generatedTodoList, setGeneratedTodoList] = useState<any[]>([]);
const selector = useSelector((state: RootState) => { return state.todo …Run Code Online (Sandbox Code Playgroud) 我对我的服务器进行了调用(是对 ibm watson 的调用)进行一些操作,如果一切正常,则返回 200 响应。
这个调用的时间超过 5000ms,cypress 可以等待。我需要等到服务器返回响应,然后我知道我的反应应用程序中会出现一个弹出窗口。
这是我从后端对 Watson 的调用:
const launchWatsonTest = (watsonData) => {
const data = {
withCredentials: true,
mode: 'cors',
headers: {
'x-access-token': watsonData.token,
},
params: {
topicId: watsonData.corpusNameId,
workspaceId: watsonData.corpusArea
}
};
return clienteAxios.post(`test-watson`, watsonData, data);
};
Run Code Online (Sandbox Code Playgroud)
我该如何等待才能继续测试?
我对 cypress 进行了这个测试:
describe("E2E CognitiveTool", function() {
it("should crear respuesta simple sin problemas", function() {
cy.visit("http://localhost:3000");
cy.contains('[data-cy="topicName"]', 'CA2');
cy.get('[data-cy="accederResponsesCA2"]').click();
cy.get('[data-cy="crearResponse"]').should('exist')
.click();
cy.get('input[name="description"]')
.type('Simple Cypres Response');
cy.get('[name="typeResponse"]').first().check({force:true});
cy.get('[name="lateral_W"]').first().check({force:true});
cy.get('[name="rolViews"]').first().check({force:true});
cy.get('[name="workLoadLevel"]').first().check({force:true});
cy.get('[data-cy="continuar"]').click();
cy.get('input[id=0]')
.type('hola');
cy.get('input[id=1]')
.type('adios');
cy.get('input[id=2]') …Run Code Online (Sandbox Code Playgroud) 我最近开始了一个项目,我使用 redux/toolkit 及其查询 API 来管理我的数据。
我尝试使用自动生成的钩子,但我从打字稿中收到错误,说他们找不到它们。这是我编写的代码示例:
export const elementsApi = api.injectEndpoints({
endpoints: (build) => ({
getElements: build.query<
{
rootParentId: string;
} & GetElementReturnType,
number
>({
query: (search) => ({ url: `Menu/GetFiles${search}` }),
transformResponse: ({ data }: { data: BackendMenuType }) => {
return {
rootParentId: data.MenuId,
...getElements(data),
};
},
providesTags: (result, _error, id) => [{ type: elements, id }],
}),
}),
});
export const { useGetElementsQuery } = elementsApi;
Run Code Online (Sandbox Code Playgroud)
当我尝试获取钩子时收到的错误消息:
Property 'useGetElementsQuery' does not exist on type 'Api<BaseQueryFn<string …Run Code Online (Sandbox Code Playgroud) 我有一组用 Redux Toolkit 编写的 API 调用。例如:
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { Contacts } from '../datamodel/Contact';
import { getAccessToken } from '../util/userContextManagement';
export const contactsApi = createApi({
reducerPath: 'contactsApi',
baseQuery: fetchBaseQuery({ baseUrl: '/api/users/current' }),
endpoints: builder => ({
getContacts: builder.query<Contacts, void>({
query: () => {
return ({
url: '/contacts',
method: 'GET',
headers: { Authorization: `Bearer ${getAccessToken()?.token}`}
});
},
})
})
})
export const { useGetContactsQuery } = contactsApi
Run Code Online (Sandbox Code Playgroud)
我可以使用函数注入访问令牌:getAccessToken()。
但是,我想在函数中检测到访问令牌已过期,并在函数返回之前使用另一个 API 调用刷新它。
不幸的是,我无法在这个函数中执行此操作,因为getAccessToken()不是反应钩子。 …
react-redux ×10
redux ×7
reactjs ×5
rtk-query ×5
typescript ×2
cypress ×1
ecmascript-6 ×1
javascript ×1
modal-dialog ×1
react-hooks ×1
react-native ×1