这是我的行动:
export function fetchNearbyUsers(user, position) {
return (dispatch) => {
const query = new Parse.Query(Parse.User);
query.withinKilometers('location', createGeoPoint(position), 10);
query.equalTo('gender', user.attributes.interest);
query.notEqualTo('objectId', user.id);
query.limit(15);
return query.find().then((users) => {
dispatch({ type: GET_NEARBYUSER_LIST, payload: users });
return Promise.resolve();
}).catch((error) => {
});
};
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,当我通过连接映射我的调度时,为什么会返回未定义。
this.props.fetchNearbyUsers(this.props.user, this.props.location).then(() => {
this.setState({ refreshing: false });
}).catch((error) => {
});
const mapDispatchToProps = dispatch => ({
fetchNearbyUsers: (user, position) => {
dispatch(fetchNearbyUsers(user, position));
},
});
Run Code Online (Sandbox Code Playgroud)
当我通过上下文访问商店时,这会返回 Promise:
const { dispatch } = this.context.store;
this.setState({ refreshing: true …Run Code Online (Sandbox Code Playgroud) 我正在尝试在 redux 上测试我的异步操作,但我没有得到它。
我正在使用 nock 和 axios,因此我尝试从 axios get 接收响应数据来测试我的操作:
describe('Async Actions', () => {
afterEach(() => {
nock.cleanAll();
});
it('should load transmissors', (done) => {
const localStorage = {
token: 'a9sd8f9asdfiasdf'
};
nock('https://tenant.contactto.care')
.get('/api/clients/1/transmissors/', {
reqheaders: { 'Authorization': "Token " + localStorage.token }
})
.reply(200, { data: [
{
"id": 12,
"zone": "013",
"client": 1,
"description": "pingente",
"identifier": "",
"general_info": ""
},
{
"id": 15,
"zone": "034",
"client": 1,
"description": "colar",
"identifier": "",
"general_info": ""
}
]});
axios.get(`/api/clients/1/transmissors/`, { …Run Code Online (Sandbox Code Playgroud) 我有这样的 action.js 文件:
import axios from 'axios';
export const SEARCH_TERM = 'SEARCH_TERM';
export const SAVE_SEARCH = 'SAVE_SEARCH';
export function search(query) {
const githubApi = `https://api.github.com/search/repositories?q=${query}&sort=stars&order=desc`;
const request = axios.get(githubApi);
return (dispatch) => {
request.then(({ data: dataFromGithub }) => {
dispatch({ type: SEARCH_TERM, payload: query });
dispatch({ type: SAVE_SEARCH, payloadOne: query, payloadTwo: dataFromGithub });
});
};
}
Run Code Online (Sandbox Code Playgroud)
使用减速器,我将用户输入的所有搜索词保存到 redux 中。然后我向 github api 发出请求并保存响应数据。
现在我遇到了一个问题,我真的不知道如何处理。
我如何编写代码来检查用户之前是否已经搜索过此查询,在这种情况下,我的应用程序不会向 github api 触发该请求。
我该如何做到这一点以及我应该将这个逻辑放在哪里?有任何想法吗?
编辑:感谢@klugjo!由于他的提示,我编写了确实有效的代码。
import React, { Component } from 'react';
import { connect } …Run Code Online (Sandbox Code Playgroud) 我试图找出将 firestore.onSnapshot 与 React-Redux 一起使用的正确方法。
componentWillMount()目前,我的操作文件中有此代码,我正在组件中调用该代码。
export const fetchCheckins = () => async (dispatch) => {
const {currentUser} = firebaseService.auth();
try {
let timestamp = (new Date());
//set timestamp for beginning of today
timestamp.setHours(0);
//get checkins today
let checkinstoday = (await firebaseService.firestore().collection(`/checkins/${currentUser.uid}/log`).where("timestamp",">=",timestamp).orderBy("timestamp","desc").get()).docs.map(doc => doc.data());
//set timestamp for beggining of week
timestamp.setDate(-(timestamp.getDay()));
//get checkins (week)
let checkinsweek = (await firebaseService.firestore().collection(`/checkins/${currentUser.uid}/log`).where("timestamp",">=",timestamp).orderBy("timestamp","desc").get()).docs.map(doc => doc.data());
//set timestamp for begging of month
timestamp.setDate(0);
//get checkins (month)
let checkinsmonth = (await firebaseService.firestore().collection(`/checkins/${currentUser.uid}/log`).where("timestamp",">=",timestamp).orderBy("timestamp","desc").get()).docs.map(doc => doc.data());
dispatch({type: …Run Code Online (Sandbox Code Playgroud) firebase react-native redux-thunk react-redux google-cloud-firestore
我正在使用 redux 和 react-native 构建一个应用程序。
我对我使用的模式很好奇。我没有遇到任何缺点,但是我没有在任何教程中看到它,这让我想知道为什么没有人这样做。
而不是将动作创建者作为连接函数中的道具传递,例如
connect(mapStateToProps,{ func1, func2 })(Component);
Run Code Online (Sandbox Code Playgroud)
我将应用程序商店导入到模块内部,我首先在其中声明了函数:
import { AppStore } from '../App';
const actionCreator = () => {
doSomethng();
appStore.dispatch({ type: 'Action' });
};
Run Code Online (Sandbox Code Playgroud)
对我来说,这使得执行异步操作变得更容易,因为我不需要中间件:
import { AppStore } from '../App';
const actionCreator = async () => {
await doSomethng();
appStore.dispatch({ type: 'Action' });
};
Run Code Online (Sandbox Code Playgroud)
我这样做是因为 js-lint 错误'no-shadow'。它让我意识到,为了使用它,我必须在组件文件中导入动作创建者,然后将其作为 prop 传递给 connect 函数,以便动作创建者能够访问调度。
import { actionCreator1, actionCreator2 } from './actionCreators';
const myComponent = (props) => {
const { actionCreator1, actionCreator2 } = props; …Run Code Online (Sandbox Code Playgroud) 我正在使用react-bootstrap-typehead在我的react/redux应用程序中开发用户搜索功能: http://ericgio.github.io/react-bootstrap-typeahead/
用户搜索调用 API 来搜索用户列表,因此我使用AsyncTypeahead组件。
由于我使用的是 Redux,因此我将加载和搜索结果存储在商店中,因此我的代码如下所示:
const { searchPeople, loading, searchResults, selectedPerson } = this.props;
<AsyncTypeahead
isLoading={loading}
options={searchResults}
labelKey="DisplayName"
clearButton
minLength={5}
onSearch={searchPeople}
onChange={handleChange}
placeholder="Search for a user..."
renderMenuItemChildren={option => (
<TypeaheadItem key={option.EmployeeID} item={option} {...this.props} />
)}
/>
Run Code Online (Sandbox Code Playgroud)
在 Redux 中调用onSearch={searchPeople}一个操作来调用 API 并将结果存储在“searchResults”中:
const searchPeople = term => async dispatch => {
dispatch({
type: REQUEST_SENT
});
const results = await dispatch(applicationActions.peopleSearch(term));
dispatch({
type: REQUEST_RECEIVED,
data: results
});
};
Run Code Online (Sandbox Code Playgroud)
我的“peopleSearch”功能存储在另一个操作中,我在其中拥有所有用户搜索功能。这就是为什么我要派去另一项行动。
const peopleSearch = searchTerm => async …Run Code Online (Sandbox Code Playgroud) ReferenceError: Cannot access 'authReducer' before initialization我在使用Reduxwithredux-toolkit和 时遇到错误redux-persist
combineReducers我有 3 个减速器,我将它们合并在一起redux-toolkit。然后我正在配置存储,将其中一个减速器持久保存到localStorage. 当我运行该应用程序时,我看到上面提到的错误消息,它指向authSlice,如果我将其注释掉,错误消息就会消失,我就能够成功运行该应用程序。我的问题是,我无法弄清楚为什么错误会专门出现,authSlice因为它或多或少与其他减速器相同。
import { configureStore, ThunkAction, Action } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import { useDispatch } from "react-redux";
import { rootReducer } from "./rootReducer";
const persistConfig = {
key: "root",
storage: storage,
whitelist: ["user"],
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
export const store = configureStore({
reducer: persistedReducer, …Run Code Online (Sandbox Code Playgroud) 我最近第一次将 Redux 放入我的应用程序中,并认为我可以正常工作,但它似乎返回了空数组。我检查了我的 Postman get 帖子,它在后端工作正常。如果数组为空,我的商店是否应该返回值,如下所示?
大概是什么问题?我有一个异步 Thunk 动作创建器和一个我认为工作正常的创建切片 Reducer。
如果我的 createSlice 索引 combineReducers 都显示为白色,这是否意味着它们无法正常工作?auth 和 message 是黄色的,我的登录工作正常,但是我没有为它们使用 createSlice。
更新:我认为这与我的 extraReducers “state: actionpayload.field”的语法有关。没有错误消息标记,但我不确定它是否在做它应该做的事情。
或者这可能与我的商店有一个 combineReducer 并通过 createSlice 的 reducer 的事实有关?(应该是 Redux 工具包的 configureStore)我的身份验证和消息工作正常,但它们不是 Redux。configureStore 是否同时允许 createSlice 和普通 switch 语句?
索引.js
export default combineReducers({
// combine the reducers
user,
fields,
article,
diveLog,
marineList,
diveSchool,
diveSpot,
admin,
auth,
message
});
Run Code Online (Sandbox Code Playgroud)
减速器
const fieldsSlice = createSlice({
name: 'diveLogFields',
initialState: {
current: [],
region: [],
diveType: [],
visibility: [],
diveSpot: [],
},
reducers: …Run Code Online (Sandbox Code Playgroud) 我使用RTKQuery来获取数据,如下所示:
export const productsApi = createApi({
reducerPath: 'productsApi',
baseQuery: fetchBaseQuery({
baseUrl: BASE_URL,
prepareHeaders,
}),
tagTypes: ['Products'],
keepUnusedDataFor: 8600,
endpoints: builder => ({
getProperties: builder.query<IProduct[], IParams>({
query: params => ({ url: 'products', params: { per_page: 40, ...params } }),
transformResponse: ({ data }: { data: IProduct[] }) => data,
providesTags: ['Products'],
}),
});
Run Code Online (Sandbox Code Playgroud)
我对 Redux Toolkit 比较陌生,在使用任何 Redux 之前直接开始使用它。从 ReduxToolkit 文档中,我找到了两种在后端捕获和放置操作的方法。
我尝试使用中间件方法使用如下代码:
export const rtkQueryErrorLogger: Middleware = (api: MiddlewareAPI) => next => action => {
if (isRejected(action)) …Run Code Online (Sandbox Code Playgroud) redux-thunk ×10
redux ×8
react-redux ×6
reactjs ×6
javascript ×2
api ×1
arrays ×1
axios ×1
firebase ×1
json ×1
nock ×1
node.js ×1
react-native ×1
rtk-query ×1