我正在尝试学习 redux 并且我正在尝试实现redux-thunk中间件。我一直在关注一些不同的教程,他们提出了类似的建议:
import thunk from "redux-thunk";
import promise from "redux-promise-middleware";
...
const middleware = applyMiddleware(promise(), thunk);
const store = createStore(reducers, middleware);
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
/Users/me/Documents/workspace/redux/node_modules/redux-thunk/index.d.ts (4,47):通用类型“Dispatch”需要 2 个类型参数。
有人可以解释一下发生了什么以及如何解决这个问题吗?
非常感谢
我有一个异步 thunk,可以从 Web 服务中获取一些信息,它可以分派三种类型的操作
FETCH_REQUESTED
FETCH_SUCCEEDED
FETCH_FAILED
Run Code Online (Sandbox Code Playgroud)
最后,如果它成功了;它返回实际的响应,或一个错误对象。
我有一个组件应该检测操作是否失败,最好通过订阅FETCH_FAILED操作并根据错误类型显示错误消息(404/401 和其他状态代码)
FETCH_REQUESTED
FETCH_SUCCEEDED
FETCH_FAILED
Run Code Online (Sandbox Code Playgroud)
我对 redux 和 react 很陌生,所以我有点不确定我是否朝着正确的方向前进,任何帮助将不胜感激。
我正在努力弄清楚我的操作应该是什么返回类型。在我使用any时一切正常,但我试图避免使用any.
export const saveValue = (value: number): any => {
return (dispatch: Dispatch<SaveValue>, getState: () => State): void => {
axios.post('www.exampleurl.com', value)
.then((response) => {
const someValueFromState = getState().stateValue;
const payload = {...response, someValueFromState}
dispatch({ type: constants.SAVE_VALUE, payload });
});
};
};
Run Code Online (Sandbox Code Playgroud)
我之前在没有使用该操作时让它工作过getState(),它看起来像这样,它返回Dispatch<SaveValue>:
export const saveValue = (value: number): Dispatch<SaveValue> => {
return (dispatch: Dispatch<SaveValue>): void => {
axios.post('www.exampleurl.com', value)
.then((response) => {
dispatch({ type: constants.SAVE_VALUE, response });
});
};
};
Run Code Online (Sandbox Code Playgroud)
但是一旦我添加了 …
我有下一个 React/Redux/Thunk 代码:
这是我对 API 的调用:
//api.js
export const categoriesFetchData = (page, parentOf) => {
return axios.get(
url +
'categories/' +
'?parent=' +
parentOf +
'&limit=10' +
'&offset=' +
(page - 1) * 10,
);
};
Run Code Online (Sandbox Code Playgroud)
这是我的动作(我假装从这个动作返回一个 axios 承诺):
//actions.js
export const subCategoriesFetchData = (page = 1, parentOf) => {
return dispatch => {
dispatch(oneCategoryLoading(true));
return api.categoriesFetchData(page, parentOf)
.then(response => {
dispatch(subCategoriesFetchDataSuccess(response.data.results));
dispatch(oneCategoryLoading(false));
})
.catch(error => {
console.log(error);
});
};
};
Run Code Online (Sandbox Code Playgroud)
在我的容器中:
const mapDispatchToProps = dispatch => {
return { …Run Code Online (Sandbox Code Playgroud) 我的组件存在重复问题,我从 api 获取了一些虚拟数据。
以下哪种方法一切正常,但是当我更改路线并转到另一个页面并返回到我列出用户对象的页面时。每次都有我的对象的重复列表。我该如何预防?
这是我的组件:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import {getAllUsers} from '../actions/user'
class users extends Component {
componentDidMount() {
this.props.getAllUsers()
}
render() {
let usersList = this.props.users.map(user => <li key={user.id}>{user.name}</li>)
return (
<div>
<h1>user list</h1>
<ul>
{usersList}
</ul>
</div>
)
}
}
const mapStateToProps = state => ({
users: state.users
})
function mapDispatchToProps(dispatch) {
return {
getAllUsers: bindActionCreators(getAllUsers, dispatch)
}
}
export default connect(mapStateToProps, …Run Code Online (Sandbox Code Playgroud) 我正在学习 Udemy 上的这个React 课程,但遇到了一个非常奇怪的错误。
我正在使用 Firebase 通过电子邮件和密码进行身份验证。当用户点击登录时,我会发送一个名为 LOGIN_USER 的操作,它设置加载状态。
当登录成功时,我会调度一个调用LOGIN_USER_SUCCESS来停止加载状态的动作。
出于某种原因,LOGIN_USER_SUCCESS直到我随机点击屏幕上的某个地方才会发生。
如果我删除该行dispatch({ type: LOGIN_USER });以禁用加载状态,则登录在几秒钟后返回成功。
My actions
-----------
export const loginUser = ({ email, password }) => {
return (dispatch) => {
dispatch({ type: LOGIN_USER });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(user => loginUserSuccess(dispatch, user))
.catch((error) => {
console.log(error);
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(user => loginUserSuccess(dispatch, user))
.catch(() => loginUserFail(dispatch));
});
};
};
const loginUserSuccess = (dispatch, user) => {
dispatch({
type: LOGIN_USER_SUCCESS,
payload: user …Run Code Online (Sandbox Code Playgroud) 我尝试在我的本机应用程序的 redux 商店中存储多个对象,但只有一个对象被保存,我是 redux 的新手,我尝试了在 StackOverflow 上找到的很多解决方案,但没有一个有效:/
结果我在我的商店:
"hives": {"hive_id": 12944, "hive_name": null}
Run Code Online (Sandbox Code Playgroud)
我想要的结果(或类似的东西):
"hives": [
1: {"hive_id": 123, "hive_name": "HelloHive"},
2: {"hive_id": 12944, "hive_name": null}]
Run Code Online (Sandbox Code Playgroud)
店铺:
const middleware = [thunk]
export const store = createStore(persistedReducer, applyMiddleware(...middleware));
export const persistor = persistStore(store);
Run Code Online (Sandbox Code Playgroud)
减速机:
const INIT_STATE = {
hives: [],
}
const hiveReducer = (state = INIT_STATE, action) => {
switch (action.type) {
case SET_HIVES:
return {
...state,
hives: action.payload,
};
[...]
Run Code Online (Sandbox Code Playgroud)
动作创建者:
export const setHives = hives => {
return …Run Code Online (Sandbox Code Playgroud) 我使用 Redux 创建了一个 CRUD 应用程序,因此,我编写了代码,并在导出组件时添加了以下行:
AddContact.PropTypes = {
addContact: PropTypes.func.isRequired
};
export default connect(null, { addContact })(AddContact);
Run Code Online (Sandbox Code Playgroud)
但是,它显示了这个错误
./src/components/contact/AddContact.js
Line 461:12: Typo in static class property declaration react/no-typos
Search for the keywords to learn more about each error.
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用storethunk从getServerSidePropsNext.js 中发送一个next-redux-wrapper。但是,我不断收到以下打字稿错误:
TS2345: Argument of type '(dispatch: any) => Promise<any>' is not assignable to parameter of type 'AnyAction'. Property 'type' is missing in type '(dispatch: any) => Promise<any>' but required in type 'AnyAction'.
Run Code Online (Sandbox Code Playgroud)
我之前没有在 Redux 中使用过 TypeScript,所以不确定我在这里做错了什么......
我的代码如下:
// page.tsx
export const getServerSideProps = wrapper.getServerSideProps(
async ({ store, params }) => {
store.dispatch(myThunkFunction(params.id));
return {
props: {
id: params.id,
},
};
});
Run Code Online (Sandbox Code Playgroud)
// thunks.ts
export const myThunkFunction = id => {
return async dispatch …Run Code Online (Sandbox Code Playgroud) 我正在学习 Redux Essentials 教程,但在第 5 部分Async Logic and Data Fetching 中遇到了一个问题。尽管本教程中未使用 TypeScript,但我仍在使用 TypeScript,因为我正在尝试同时学习 Redux 和 TypeScript。
在Checking Thunk Results in Components一节中,我在调用 Redux 的unwrapResult函数时遇到了一个我无法弄清楚的类型错误。
这是错误:
TypeScript error in redux-essentials-example-app/src/features/posts/AddPostForm.tsx(34,22):
Argument of type 'AsyncThunkAction<Post, InitialPost, {}>' is not assignable to parameter of type 'ActionTypesWithOptionalErrorAction'.
Property 'payload' is missing in type 'AsyncThunkAction<Post, InitialPost, {}>' but required in type '{ error?: undefined; payload: any; }'. TS2345
32 | setAddRequestStatus("pending");
33 | const result = await dispatch(addNewPost({ …Run Code Online (Sandbox Code Playgroud) redux ×10
redux-thunk ×10
reactjs ×8
react-redux ×5
typescript ×4
react-native ×3
firebase ×1
javascript ×1
next.js ×1