我应该如何在redux中实现以下逻辑:有2个动作:sync和async.让我们说它的validate()和save().当用户单击validate()执行的按钮时,它会更改isValid状态存储中的某个变量.然后,如果isValid执行保存操作.
我知道我不应该试图从传奇中发出雷鸣声,这与redux-saga试图做的事情背道而驰.但是我在一个相当大的应用程序中工作,大部分代码都是用thunk开发的,我们正在逐位迁移,需要从一个传奇内部发送一个thunk.thunk无法更改,因为它被用在其他部分(一个返回一个promise的thunk),所以它会打破很多东西.
configureStore:
const store = createStore(
rootReducer,
initialState,
compose(applyMiddleware(thunk, sagaMiddleware))
);
Run Code Online (Sandbox Code Playgroud)
佐贺:
// Saga (is called from a takeEvery)
function* watchWarehouseChange(action) {
const companyId = yield select(Auth.id);
// We use cookies here instead of localStorage so that we persist
// it even when the user logs out. (localStorage clears on logout)
yield call(Cookies.set, `warehouse${companyId}`, action.warehouse);
// I want to dispatch a thunk here
yield put.resolve(syncItems);
// put(syncItems) doesn't work either
}
Run Code Online (Sandbox Code Playgroud)
咚:
export function syncItems() {
console.log('first!');
return dispatch => …Run Code Online (Sandbox Code Playgroud) 我想知道我在 ReactNative/Redux 应用程序中所做的是否是错误的。这就是我处理异步操作的方式。
我的组件.js
componentDidMount() {
fetch('https://www.mywebsite.com')
.then(data => this.props.handleApiSuccess(data)) // injected as props by Redux
.catch(err => this.props.handleApiError(err)); // injected as props by Redux
}
Run Code Online (Sandbox Code Playgroud)
我可能应该做的 redux-thunk 方式
export const handleApiCall = () => dispatch => {
fetch('https://www.mywebsite.com')
.then(data => dispatch(handleApiSuccess(data)))
.catch(err => dispatch(handleApiError(err)));
}
Run Code Online (Sandbox Code Playgroud)
第一部分的做法有什么问题吗?
我试图在用户提交表单时分派一个动作。假设我有一个提交按钮,它会触发onSubmit表单上的事件(最终会在处理表单请求时显示一个微调图标,但此时,提交按钮只显示一个true或false值,表示微调是否正在显示)。
登录页面.js
import React from 'react';
import { Link } from 'react-router-dom';
export class LoginPage extends React.Component {
constructor(props) {
super(props);
this.handleLogin = this.handleLogin.bind(this);
}
handleLogin(e) {
e.preventDefault();
let email = document.getElementById('userEmail').value;
let password = document.getElementById('userPassword').value;
this.props.loginHandler(email, password);
}
render() {
return (
<form onSubmit={ this.handleLogin }>
<input type="submit" value={ this.props.requestingLogin } />
</form>
);
}
}
export default LoginPage;
Run Code Online (Sandbox Code Playgroud)
登录页面容器.js
import React from 'react';
import { connect } from 'react-redux';
import LoginPage from …Run Code Online (Sandbox Code Playgroud) 我想根据发出的请求单独显示每个请求的加载程序,假设在仪表板中我有多个小部件,并且它们都有不同的 api 调用,我想为每个发出的请求显示不同的加载程序,
一种方法是为每个发出的请求添加isLoading标志,我认为随着应用程序的增长,这不是一个好的解决方案,并且我正在寻找可以处理来自一个标志的多个请求的解决方案
那么我应该如何根据每个请求制作动态的单独加载器
下面是我的减速器和动作
减速器
export const intialstate = {
isAuth: false,
isLoading: false,
btnDisable: false
};
export default function(state = intialstate, action) {
switch (action.type) {
case API_REQUEST:
return {
...state,
isLoading: true,
};
case API_SUCCESS:
return {
...state,
isLoading: false,
isError: null
};
case API_FAILURE:
return {
...state,
isError: action.payload,
isLoading: false,
};
// no default
}
return state;
}
Run Code Online (Sandbox Code Playgroud)
动作.js
export const AnyAPIRequest = () => {
return (dispatch) => {
dispatch({
type: …Run Code Online (Sandbox Code Playgroud) 我正在使用 getState() 检索状态的一部分以从事件处理程序中的状态中过滤一些值(在调度操作并使用新状态切片更新存储之前)但是更改 getState 的结果似乎改变了实际店铺。
考虑以下:
const filterInPlace = (array, predicate) => {
let end = 0;
for (let i = 0; i < array.length; i++) {
const obj = array[i]
if (predicate(obj)) {
array[end++] = obj
}
}
array.length = end
}
//some event handler
...
const forDeletion = new Set([...ids])
let currentState = getState().home.lists
filterInPlace(currentState, obj => !forDeletion.has(obj.rowid))
dispatch(handleSelectLists(ids)) //Leads to an action and reducer
Run Code Online (Sandbox Code Playgroud)
getState() 会改变存储吗?
我目前正在尝试从 react-redux connect() hoc 切换到将在 react-redux 7.1.x 中引入的新 hooks api。
一些示例已经在工作,但我无法解决以下问题。我有以下 redux 功能:
export const translate = key => (dispatch, getState) =>
getState().translations.data[key] || "";
Run Code Online (Sandbox Code Playgroud)
它将密钥翻译成给定的语言。在我的组件中,我目前正在调用这样的函数:
import React, { Fragment, useCallback } from "react";
import { Button } from "@material-ui/core";
import { useDispatch } from "react-redux";
import { LanguageActions } from "../../redux/actions";
export default function LanguageSwitcher() {
const dispatch = useDispatch();
const translateKey = useCallback(
key => dispatch(LanguageActions.translate(key)),
[]
);
const requestCustomLanguage = useCallback(
requestedLanguage =>
dispatch(LanguageActions.loadCustomLanguage(requestedLanguage)),
[]
);
return …Run Code Online (Sandbox Code Playgroud) 我正在使用 redux 和 redux thunk 进行反应。我有一个动作,我正在发出网络请求。使用 useSelector 我从 redux 存储中获取数据。我有一个问题,每次分派动作时组件都会重新渲染。我希望该组件仅在数据更改时重新渲染。我已经尝试使用shallowEqual 作为useSelector 的第二个参数。但它不起作用。我已将其压缩到此沙箱中的最小示例。在控制台中,您可以看到组件随着每个网络请求重新呈现。这是代码和框:https ://codesandbox.io/s/useselector-js6j0 ? file =/ src/App.js:885-1294
这是代码:
function LevelThree() {
console.log(`Level three calls: ${++levelThreeCalls}`);
const contextData = useSelector(state => state.data);
console.log(contextData);
const dispatch = useDispatch();
useInterval(() => {
dispatch(updateData());
}, 1000);
return (
<div>
<button onClick={() => dispatch(updateData())}>Change context</button>
{contextData[0].userId}
</div>
);
Run Code Online (Sandbox Code Playgroud)
}
我目前正在设置我的 RTK(Redux 工具包)并进行了一些小测试。这是我的代码:
商店/index.js
import { configureStore } from '@reduxjs/toolkit'
import { loginSliceReducer } from './views/page/login/loginSlice'
export default configureStore({
reducer: {
login: loginSliceReducer
}
})
Run Code Online (Sandbox Code Playgroud)
登录Slice.js
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import ApiService from '../../services/ApiService'
export const authorize = createAsyncThunk(
'api/authorize',
async (email, password) => {
const response = await ApiService.post(email, password)
return response.data
}
)
export const loginSlice = createSlice({
name: 'login',
initialState: {
loading: true,
token: null,
data: []
},
reducers: {
updateState: (state, action) => …Run Code Online (Sandbox Code Playgroud) 我很喜欢 redux-toolkit,但我想知道是否有办法为任何被拒绝的 thunk 添加通用错误处理程序?就像浏览器有可以监听的unhandledrejection事件一样,我想向我的错误跟踪器报告任何被拒绝的承诺。
redux-thunk ×10
redux ×9
reactjs ×8
javascript ×7
react-redux ×4
react-hooks ×2
react-native ×1
redux-saga ×1