将函数从 pure react 转换为 redux react [英] Converting functions from pure react to redux react
问题描述
在纯 React 中,我编写了一个在 componentDidMount ()
中调用的函数:
getTasks = (userId, query, statusTask, pageNumber) =>{让检查 = {};轴({网址:`/api/v1/beta/${userId}`,方法:'获取'}).then(res => {检查 = res.data;如果(res.data){this.setState({检查运行:res.data,checkRunningId: res.data.id});this.utilizeTimes(res.data.task_id);}}).catch(错误=> {控制台日志(错误);}).then(() => {常量参数 = {排序:'名称'};如果(查询){参数['过滤器[qwp]'] = 查询;如果(this.state.tasks[0]){this.setState({selectedId: this.state.tasks[0].id,selectedTabId: this.state.tasks[0].id});}}轴({url: '/api/v1//任务',方法:'获取',参数}).then(res => {如果(res.status === 200 && res.data){this.setState({任务:res.data,lengthArrayTasks: parseInt(res.headers['x-pagination-total-count'])});如果 (!check && res.data && res.data[0]) {this.setState({selectedTabId: res.data[0].id,});this.load(res.data[0].id);}让 myArrayTasks = [];myArrayTasks = res.data;让 findObject = myArrayTasks.find(task => task.id === this.state.runningTimerTask.id);如果 (!findObject &&this.state.runningTimerTask &&this.state.runningTimerTask.id &&this.state.query === ''){this.setState({任务:[this.state.runningTimerTask, ...myArrayTasks]});}}}).catch(错误=> {控制台日志(错误);});});};
我正在尝试将其重写为 redux,但结果不佳.首先它发出一个请求/api/v1/beta/${userId}
,将答案写入变量check
.check
传递到下一个then
.在接下来的 then
执行请求 '/api/v1//tasks' 有人可以帮我吗?我要求提供一些提示.这有点复杂吗?
到目前为止,我已经成功地创建了这样的东西:
商店
import { createStore, applyMiddleware } from 'redux';从redux-thunk"导入 thunk;从'../reducers'导入rootReducer;const store = createStore(rootReducer, applyMiddleware(thunk));导出默认商店;
操作
export const RUNNING_TIMER = 'RUNNING_TIMER';导出 const GET_TASKS = 'GET_TASKS';export const FETCH_FAILURE = 'FETCH_FAILURE';export const runningTimer = (userId, query, statusTask, pageNumber) =>调度 =>{控制台日志(用户 ID);轴({网址:`/api/v1/beta/${userId}`,方法:'获取'}).then(({数据}) => {派遣({类型:RUNNING_TIMER,有效载荷:数据});}).catch(错误=> {控制台日志(错误);调度({ 类型:FETCH_FAILURE });}).then(() => {常量参数 = {排序:'名称'};轴({url: '/api/v1//任务',方法:'获取',参数}).then(({数据}) => {派遣({类型:GET_TASKS,有效载荷:数据});}).catch(错误=> {控制台日志(错误);});});};
减速器
import { RUNNING_TIMER, GET_TASKS } from '../actions';const isRunningTimer = (state = {}, action) =>{const { 类型,有效载荷 } = 动作;开关(类型){案例 RUNNING_TIMER:返回 {checkRunningTimer:有效载荷,checkRunningTimerId: 有效载荷 &&有效载荷.id ?有效载荷.id:空};休息;案例 GET_TASKS:返回 {任务:有效载荷,lengthArrayTasks: parseInt(action.headers['x-pagination-total-count'])};默认:返回状态;}};const rootReducer = combineReducers({ isRunningTimer });导出默认的 rootReducer;
应用
class App 扩展组件 {构造函数(){极好的();this.state = {名称:'反应'};}componentDidMount() {this.props.runningTimer();}使成为() {返回 (<div>
);}}const mapStateToProps = state =>{const { isRunningTimer } = 状态;返回 {正在运行的定时器};};const mapDispatchToProps = dispatch =>({runningTimer: (userId, query, statusTask, pageNumber) =>调度(运行定时器()),});导出默认连接(mapStateToProps,mapDispatchToProps)(应用程序);
第 1 点考虑您的状态设计.
我发现考虑状态对象在给定时间点的样子很有用.
这是我的应用程序中使用的 initialState 示例.
const initialState = {杂货店:空,坐标:{纬度:37.785,经度:-122.406}};
这是在 createStore 中注入的.
分解您的应用程序状态对象/属性也应该有助于您简化操作.
编号 2
考虑分解你的行为.
我的想法,将动作代码解耦,在 .then 在第二个 .then .(考虑将结果保存在用户:对象中的某处)
.then(response => {常量数据 = response.data.user;设置用户(数据);}).catch(错误=> {console.log('您的提取操作出现问题:' + error.message);})功能集用户(数据){派遣({类型:FETCH_USERS,有效载荷:数据});}
这是指 SOLID 设计原则中的 S.单一职责原则.
https://devopedia.org/solid-design-principles
数字 3
考虑这一点,如果getUser"信息获取失败.
将进程/响应分开将允许更干净地调试应用程序.例如,用户 api 失败或 getTask api 失败等.
<小时>关于 redux 的更多资源.https://redux.js.org/introduction/learning-resources#在 Redux 中思考
In pure react, I have written a function that I call in componentDidMount ()
:
getTasks = (userId, query, statusTask, pageNumber) => {
let check = {};
axios({
url: `/api/v1/beta/${userId}`,
method: 'GET'
})
.then(res => {
check = res.data;
if (res.data) {
this.setState({
checkRunning: res.data,
checkRunningId: res.data.id
});
this.utilizeTimes(res.data.task_id);
}
})
.catch(error => {
console.log(error);
})
.then(() => {
const params = {
sort: 'name'
};
if (query) {
params['filter[qwp]'] = query;
if (this.state.tasks[0]) {
this.setState({
selectedId: this.state.tasks[0].id,
selectedTabId: this.state.tasks[0].id
});
}
}
axios({
url: '/api/v1//tasks',
method: 'GET',
params
})
.then(res => {
if (res.status === 200 && res.data) {
this.setState({
tasks: res.data,
lengthArrayTasks: parseInt(res.headers['x-pagination-total-count'])
});
if (!check && res.data && res.data[0]) {
this.setState({
selectedTabId: res.data[0].id,
});
this.load(res.data[0].id);
}
let myArrayTasks = [];
myArrayTasks = res.data;
let findObject = myArrayTasks.find(task => task.id === this.state.runningTimerTask.id);
if (
!findObject &&
this.state.runningTimerTask &&
this.state.runningTimerTask.id &&
this.state.query === ''
) {
this.setState({
tasks: [this.state.runningTimerTask, ...myArrayTasks]
});
}
}
})
.catch(error => {
console.log(error);
});
});
};
I am trying to rewrite it to redux, but with poor results. First it makes one request / api / v1 / beta / $ {userId}
, writes the answer in the variable check
. check
passes to the nextthen
. In the next then
carries out the request '/ api / v1 // tasks' Can somebody help me? I am asking for some tips. Is this somehow complicated?
So far, I've managed to create something like this:
store
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
actions
export const RUNNING_TIMER = 'RUNNING_TIMER';
export const GET_TASKS = 'GET_TASKS';
export const FETCH_FAILURE = 'FETCH_FAILURE';
export const runningTimer = (userId, query, statusTask, pageNumber) => dispatch => {
console.log(userId);
axios({
url: `/api/v1/beta/${userId}`,
method: 'GET'
})
.then(({ data }) => {
dispatch({
type: RUNNING_TIMER,
payload: data
});
})
.catch(error => {
console.log(error);
dispatch({ type: FETCH_FAILURE });
})
.then(() => {
const params = {
sort: 'name'
};
axios({
url: '/api/v1//tasks',
method: 'GET',
params
})
.then(({ data }) => {
dispatch({
type: GET_TASKS,
payload: data
});
})
.catch(error => {
console.log(error);
});
});
};
reducer
import { RUNNING_TIMER, GET_TASKS } from '../actions';
const isRunningTimer = (state = {}, action) => {
const { type, payload } = action;
switch (type) {
case RUNNING_TIMER:
return {
checkRunningTimer: payload,
checkRunningTimerId: payload && payload.id ? payload.id : null
};
break;
case GET_TASKS:
return {
tasks: payload,
lengthArrayTasks: parseInt(action.headers['x-pagination-total-count'])
};
default:
return state;
}
};
const rootReducer = combineReducers({ isRunningTimer });
export default rootReducer;
App
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
componentDidMount() {
this.props.runningTimer();
}
render() {
return (
<div>
</div>
);
}
}
const mapStateToProps = state => {
const { isRunningTimer } = state;
return {
isRunningTimer
};
};
const mapDispatchToProps = dispatch => ({
runningTimer: (userId, query, statusTask, pageNumber) => dispatch(runningTimer()),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
Number 1 Consider your state design.
I find it useful to consider what the state object would look like at a given point in time.
Here is an example of initialState used in an application of mine.
const initialState = {
grocers: null,
coords: {
latitude: 37.785,
longitude: -122.406
}
};
This is injected at the createStore.
Breaking down your application state object/properties, should assist you in making your actions simpler as well.
Number 2
Consider breaking down your actions.
My thoughts, decouple the action code, at the .then at the second .then .(Consider saving the results somewhere in a user: object)
.then(response => {
const data = response.data.user;
setUsers(data);})
.catch(error => {
console.log('There has been a problem with your fetch operation: ' + error.message);
})
function setUsers(data){
dispatch({
type: FETCH_USERS,
payload: data
});
}
This refers to the S in SOLID design principles. Single Responsibility Principle.
https://devopedia.org/solid-design-principles
Number 3
Consider this, if the 'getUser' info fetch fails.
Having the process/response separated will allow the application to be debugged more cleanly. In example, the user api failed or the getTask api failed, etc.
More resources on redux. https://redux.js.org/introduction/learning-resources#thinking-in-redux
这篇关于将函数从 pure react 转换为 redux react的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!