错误本身:
(alias) deleteCategory(id: number): (dispatch: Dispatch<AnyAction>) => void
import deleteCategory
Argument of type '(dispatch: Dispatch) => void' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type '(dispatch: Dispatch) => void' but required in type 'AnyAction'.ts(2345)
Run Code Online (Sandbox Code Playgroud)
有问题的代码:
export function getCategoryList(
categories: CategoryType[],
dispatch: Dispatch
) {
return categories.map((category: CategoryType) => ({
...category,
onDelete: () => {
dispatch(deleteCategory(category._id)); //FIXME: Fix this. Error Appears here
},
}));
}
Run Code Online (Sandbox Code Playgroud)
删除类别的实现:
export const deleteCategory = (id: number) => (dispatch: Dispatch) …Run Code Online (Sandbox Code Playgroud) 我无法设置getState()to的返回类型RootState。我正在使用打字稿和 VSCode。我必须将类型设置为any,这会停止该对象上的 IntelliSense。下面是有问题的代码:
export const unsubscribeMeta = createAsyncThunk(
'meta/unsubscribe',
async (_, { getState }) => {
const { meta } = getState() as any;
const res = await client.post<apiUnsubscribeResponse>(
`/meta/unsubscribe/${meta.subscriptionId}`
);
return res.data.data;
}
);
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用RootState而不是any,VSCode 会在模块中标记许多错误。我相信这是由于商店和这个切片的循环依赖。我RootState在模块中的许多地方使用了选择器,没有问题。有没有解决的办法?
对于我的 React 应用程序,我构建了许多自定义中间件并在applyMiddleware(). 因为我有这么多,redux 存储文件看起来有点拥挤。将它们全部applyMiddleware()传递到函数中或将它们导入到函数内的单独文件中,然后将该函数传递到函数中applyMiddleware()以保持清洁是一种好习惯吗?
// Redux store
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const store = createStore(
reducers,
composeEnhancers(
applyMiddleware(...xMdl, ...yMdl, ...zMdl, ...nAmountsOfMdl),
)
);
Run Code Online (Sandbox Code Playgroud) 我正在寻找thunk并试图弄清楚如何实现api调用.它没有用,所以我回到了基础.当我点击它'Getting here!在控制台中显示的按钮时,但是当我没有显示任何内容时console.log(dispatch).我在这里错过了什么吗?
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { connect, Provider } from 'react-redux';
import thunk from 'redux-thunk'
import axios from 'axis';
const store = createStore(
reducer,
applyMiddleware(thunk)
);
function fetchUser() {
return axios.get('https://randomuser.me/api/');
}
function addUser() {
console.log('Getting here');
return (dispatch) => {
console.log(dispatch) //not showing anything
return fetchUser().then(function(data){
console.log(data);
});
};
}
class App extends React.Component {
addUser() {
addUser();
}
render() {
return …Run Code Online (Sandbox Code Playgroud) 说我有这样的代码:
import { Action, Dispatch } from 'redux';
import { ThunkAction } from 'redux-thunk';
interface StateTree {
field: string;
}
function myFunc(action: Action | ThunkAction<void, StateTree, void>,
dispatch: Dispatch<StateTree>) {
dispatch(action); // <-- This is where the error comes from
}
Run Code Online (Sandbox Code Playgroud)
...我从TypeScript编译器中得到此错误:
ERROR in myFile.ts:x:y
TS2345: Argument of type 'Action | ThunkAction<void, StateTree, void>' is not assignable to parameter of type 'Action'.
Type 'ThunkAction<void, StateTree, void>' is not assignable to type 'Action'.
Property 'type' is missing in type 'ThunkAction<void, StateTree, …Run Code Online (Sandbox Code Playgroud) 我正在尝试发送一个动作.我找到了一些行动的例子,但没有我的那么复杂.
你能给我一个暗示吗?我究竟做错了什么?
我正在使用TypeScript,并且最近删除了所有类型并尽可能地简化了我的代码.
我正在使用redux-thunk和redux-promise,如下所示:
import { save } from 'redux-localstorage-simple';
import thunkMiddleware from 'redux-thunk';
import promiseMiddleware from 'redux-promise';
const middlewares = [
save(),
thunkMiddleware,
promiseMiddleware,
];
const store = createStore(
rootReducer(appReducer),
initialState,
compose(
applyMiddleware(...middlewares),
window['__REDUX_DEVTOOLS_EXTENSION__'] ? window['__REDUX_DEVTOOLS_EXTENSION__']() : f => f,
),
);
Run Code Online (Sandbox Code Playgroud)
组件 - Foo组件:
import actionFoo from 'js/actions/actionFoo';
import React, { Component } from 'react';
import { connect } from 'react-redux';
class Foo {
constructor(props) {
super(props);
this._handleSubmit = this._handleSubmit.bind(this);
}
_handleSubmit(e) {
e.preventDefault();
this.props.doActionFoo().then(() => {
// …Run Code Online (Sandbox Code Playgroud) 我对Jest很陌生,不可否认我是测试异步代码的专家......
我有一个简单的Fetch帮手:
export function fetchHelper(url, opts) {
return fetch(url, options)
.then((response) => {
if (response.ok) {
return Promise.resolve(response);
}
const error = new Error(response.statusText || response.status);
error.response = response;
return Promise.reject(error);
});
}
Run Code Online (Sandbox Code Playgroud)
并像这样实现它:
export function getSomeData() {
return (dispatch) => {
return fetchHelper('http://datasource.com/').then((res) => {
dispatch(setLoading(true));
return res.json();
}).then((data) => {
dispatch(setData(data));
dispatch(setLoading(false));
}).catch(() => {
dispatch(setFail());
dispatch(setLoading(false));
});
};
}
Run Code Online (Sandbox Code Playgroud)
但是,我想测试在正确的情况下以正确的顺序触发正确的调度.
这曾经很容易用a sinon.spy(),但我无法弄清楚如何在Jest中复制它.理想情况下,我希望我的测试看起来像这样:
expect(spy.args[0][0]).toBe({
type: SET_LOADING_STATE,
value: true,
});
expect(spy.args[1][0]).toBe({
type: SET_DATA,
value: {...},
}); …Run Code Online (Sandbox Code Playgroud) 我在网上发现了类似的问题,但是redux-thunk通过调用Action 时没有解决方案store.dispatch()。
我有以下内容action:
export class DBActions {
static startDatabase(): ThunkAction<Promise<void>, {}, IClientState, AnyAction> {
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>, getState: () => IClientState): Promise<void> => {
return new Promise<void>((resolve) => {
dispatch(DBActions.connectDatabase())
setTimeout(() => {
let connection: (Connection | undefined) = getDBConnection(getState())
if (connection) {
dispatch(DBActions.getImports(connection))
resolve()
}
}, 2000)
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过添加到mapDispatchToProps组件中时,此方法可以正常工作,但store.ts在定义a之后直接在my内部调用时,则不会出现问题store。store.dispatch(DBActions.startDatabase())导致:
TS2345: Argument of type 'ThunkAction<Promise<void>, {}, {}, AnyAction>' is not …Run Code Online (Sandbox Code Playgroud) 我正在redux-thunk使用异步操作创建器。结果也返回给相应的调用者。
function fetchUserName(userId: number): Promise<string> {
return Promise.resolve(`User ${userId}`)
}
function requestUserName(userId: number) {
return (dispatch: Dispatch) => {
return fetchUserName(userId).then(name => {
dispatch({
type: 'SET_USERNAME',
payload: name,
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
这样,存储被更新,同时允许组件直接处理响应。
function User() {
const dispatch = useDispatch()
useEffect(() => {
dispatch(requestUserName(1))
.then(name => {
console.log(`user name is ${name}`)
})
.catch(reason => {
alert('failed fetching user name')
})
}, [])
}
Run Code Online (Sandbox Code Playgroud)
这是按预期工作的,但由于类型无效,它不会被 TypeScript 编译。
dispatch由归国useDispatch不被识别为一个返回无极等打字稿认为,一个功能Property 'then' does not exist on type …我将 Redux Toolkit 与下面的 thunk/slice 一起使用。与其在 state 中设置错误,我想我可以通过等待 thunk 承诺解决来在本地处理它们,使用这里提供的示例。
我想我可以避免这样做,也许我应该通过error在 state 中设置 an 来避免这样做,但我有点想了解我在这方面出了什么问题。
Argument of type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' is not assignable to parameter of type 'Action<unknown>'.
Property 'type' is missing in type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' but required in type 'Action<unknown>'
Run Code Online (Sandbox Code Playgroud)
传递resultAction到时出现错误match:
const onSubmit = async (data: LoginFormData) => {
const resultAction = await dispatch(performLocalLogin(data));
if (performLocalLogin.fulfilled.match(resultAction)) {
unwrapResult(resultAction)
} else {
// resultAction.payload is not available either …Run Code Online (Sandbox Code Playgroud) redux ×10
redux-thunk ×10
reactjs ×7
typescript ×5
react-redux ×4
async-await ×1
fetch ×1
javascript ×1
jestjs ×1