我目前正在尝试构建一个简单的react-redux应用程序,该应用程序在后端具有学生和校园数据.OnEnter以前在这里工作,但它在新的react-router中不存在.
此应用程序尝试在开始时加载初始数据,而不是在每个实际组件中执行componentDidMount.这是推荐的方法,还是有其他我不知道的模式?
/* -------------------< COMPONENT >------------------- */
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Home from './components/Home';
import Students from './components/Students';
const Routes = ({ getInitialData }) => {
return (
<Router>
<div>
<Route exact path="/" component={Home} onEnter={getInitialData} />
<Route path="/students" component={Students} />
<Route path="*" component={Home} />
</div>
</Router>
);
};
/* -------------------< CONTAINER >-------------------- */
import { connect } from 'react-redux';
import receiveStudents from './reducers/student';
import receiveCampuses from './reducers/campus';
const mapState = …Run Code Online (Sandbox Code Playgroud) 我正在从某个其他组件调度一个动作,并且商店正在使用svgArr属性进行更新,但是通过以下无状态组件connect'ed到商店,它在商店更改时没有得到更新svgArr.
它是如何表现的,因为它是一个无状态的组件?或者我做错了什么?
const Layer = (props) => {
console.log(props.svgArr);
return (<div style = {
{
width: props.canvasWidth,
height: props.canvasWidth
}
}
className = {
styles.imgLayer
} > hi < /div>);
};
connect((state) => {
return {
svgArr: state.svgArr
};
}, Layer
);
export default Layer;
Run Code Online (Sandbox Code Playgroud) 在我用于React Redux项目的Boilerplate中,我在代码中看到了这条评论:
这是一个thunk,这意味着它是一个立即返回延迟评估函数的函数.它对于创建异步操作非常有用,特别是与redux-thunk结合使用时!
现在,如果我理解正确,懒惰评估是返回函数的过程.返回函数的目的是什么,以及如何创建异步操作?
哦,还是一个thunk只是一个功能?
我有一个redux thunk动作,它获取一些数据然后调度一些动作(这里没有显示代码,但是你可以在下面的demo链接中找到它)
export const fetchPosts = (id: string) => (dispatch: Dispatch<TActions>) => {
return fetch('http://example.com').then(
response => {
return response.json().then(json => {
return "Success message";
});
},
err => {
throw err;
}
);
};
Run Code Online (Sandbox Code Playgroud)
而不是在我的组件我用mapDispatchToProps用bindActionCreators,从我的组件调用该函数如下所示:
public fetchFunc() {
this.props.fetchPosts("test").then(
res => {
console.log("Res from app", res);
},
err => {
console.log("Err from app", err);
}
);
}
Run Code Online (Sandbox Code Playgroud)
由于我使用的是typescript,我需要在Props中定义这个函数的类型
interface IProps {
name?: string;
posts: IPost[];
loading: boolean;
fetchPosts: (id: string) => Promise<string | Error>;
} …Run Code Online (Sandbox Code Playgroud) 我在使用 redux 工具包和 next js 时遇到错误。我面临着这个遗留警告-
/!\ You are using legacy implementaion. Please update your code: use createWrapper() and wrapper.useWrappedStore().
我不明白问题实际发生在哪里,我必须更新我的代码。
这是代码-
这是store.ts-
import { Action, configureStore, ThunkAction } from "@reduxjs/toolkit";
import { createWrapper, HYDRATE } from "next-redux-wrapper";
import { combinedReducer } from "./Reducer";
const reducer: typeof combinedReducer = (state, action) => {
if (action.type === HYDRATE) {
const nextState = {
...state,
...action.payload,
};
return nextState;
} else {
return combinedReducer(state, action);
}
};
export const makeStore …Run Code Online (Sandbox Code Playgroud) 几个月以来,我一直在使用React,Redux.生态系统中最令人困惑的部分之一是异步数据流.有很多很好的解决方案,为您的问题选择合适的解决方案是困难的部分.
在我的应用程序中,动作创建者大多数都有异步axios [ajax]调用我的后端apis.将Redux-Promise注入中间件可以解决异步数据流的问题.
考虑到可扩展的应用程序,我可能需要在我的动作创建者中链接多个axios调用.我想我仍然可以使用Redux-Promise作为中间件,这将在我的应用程序中处理异步数据流.
一般来说,团队更倾向于使用Redux-Thunk,我觉得这个问题的语法更复杂.考虑到我的大多数动作创建者只进行了axios调用(promises),我需要在评估这两个框架时提出建议.我见过的讨论了大量的终极版-咚这里.我明白thunk是如何有用的..但是当我只使用Promises时,我需要更多的澄清来评估Redux-Promise和Redux-Thunk.哪种中间件在这种情况下更好?为什么?使用Redux-Thunk而不是Redux-Promise可以获得哪些优势?或者没有?
我正在试图找出如何以及在何处加载数据(即我的动作上的调用调度)for react + redux + thunk中的选择框.我不确定它是否应该放在我的App容器的构造函数中,或者我应该将它加载到我的组件中(在我的示例中:"MyDropdown")
我的主要应用:
import MyDropdown from '../components/mydropdown';
// Should i import my action here and then...
// import { loadData } from '../actions';
class App extends Component {
render() {
return (
<div className="page-content">
<div className="option-bar">
// SEND it as a PROP inside MyDropdown...
<MyDropdown />
</div>
</div>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
我的组件
// OR.. Should i load it in my MyDropdown component here?
import { loadData } from '../actions';
class MyDropdown …Run Code Online (Sandbox Code Playgroud) 我正在尝试对商店进行多项更改,但在完成所有更改之前不会进行渲染.我想用redux-thunk做到这一点.
这是我的动作创作者:
function addProp(name, value) {
return { type:'ADD_PROP', name, value }
}
function multiGeoChanges(...changes) {
// my goal here is to make multiple changes to geo, and make sure that react doesnt update the render till the end
return async function(dispatch, getState) {
for (let change of changes) {
dispatch(change);
await promiseTimeout(2000);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我派遣我的异步动作创建者:
store.dispatch(multiGeoChanges(addProp(1, "val1"), addProp(2, "val2"), addProp(3, "val3")));
Run Code Online (Sandbox Code Playgroud)
然而,这导致每个后面的渲染反应dispatch.我是redux-thunk的新手,我从未使用异步中间件,但我认为它可以帮助我.
我已经用这样的打字稿设置了一个 redux thunk 函数:
export const fetchActivities = (): AppThunk => async dispatch => {
dispatch(fetchActivitiesRequest())
try {
const res = await fetch("/activities")
const body = await res.json()
dispatch(fetchActivitiesSuccess(body))
} catch (err) {
dispatch(fetchActivitiesError(err))
}
}
Run Code Online (Sandbox Code Playgroud)
AppThunk 只是从 ThunkAction 类型派生的类型,具有以下类型参数:
export type AppThunk<ReturnType = void> = ThunkAction<ReturnType, {}, null, Action<string>>
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我尝试为我的操作设置单元测试时,以及当我尝试像这样分派 thunk 操作时:
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore({ activities: [] })
store.dispatch(actions.fetchActivities())
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
Argument of type 'ThunkAction<void, {}, null, Action<string>>' is not assignable …Run Code Online (Sandbox Code Playgroud) 错误:
\nArgument of type \'(dispatch: Dispatch<ShopDispatchTypes>) => Promise<void>\' is not assignable to parameter of type \'AnyAction\'.\nuseEffect(() => {\n dispatch(GetShops());\n}, []);\nRun Code Online (Sandbox Code Playgroud)\n我正在尝试使用 Typescript 实现 redux-thunk。我使用react、typescript和redux-thunk创建了简单的购物卡应用程序,但遇到了上述问题。\n下面是我的代码片段\xe2\x80\x99s。如果您需要更多信息,请随时询问。
\n商店.actionTypes.ts
\nexport const SHOP_LOAD_START = \'SHOP_LOAD_START\';\nexport const SHOP_LOAD_SUCCESS = \'SHOP_LOAD_SUCCESS\';\nexport const SHOP_LOAD_ERROR = \'SHOP_LOAD_ERROR\';\n\nexport type Shop = {\n id: string;\n name: string;\n};\n\nexport type ShopType = {\n shops: Shop[];\n};\n\nexport interface ShopLoadStart {\n type: typeof SHOP_LOAD_START;\n}\n\nexport interface ShopLoadError {\n type: typeof SHOP_LOAD_ERROR;\n}\n\nexport interface ShopLoadSuccess {\n type: typeof SHOP_LOAD_SUCCESS;\n payload: ShopType;\n}\n\nexport type ShopDispatchTypes = ShopLoadStart …Run Code Online (Sandbox Code Playgroud) redux-thunk ×10
redux ×8
reactjs ×7
react-redux ×5
typescript ×4
javascript ×3
axios ×1
react-router ×1