Umb*_*bro 4 javascript reactjs redux react-redux
在纯粹的反应中,我编写了一个调用的函数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);
});
});
};
Run Code Online (Sandbox Code Playgroud)
我正在尝试将其重写为redux,但效果不佳。首先,它发出一个请求/ api / v1 / beta / $ {userId},将答案写入变量check。check传递到下一个then。接下来then执行请求'/ api / v1 //任务'有人可以帮我吗?我要求一些提示。这有点复杂吗?
到目前为止,我已经成功创建了以下内容:
商店
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
Run Code Online (Sandbox Code Playgroud)
行动
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);
});
});
};
Run Code Online (Sandbox Code Playgroud)
减速器
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;
Run Code Online (Sandbox Code Playgroud)
应用程式
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);
Run Code Online (Sandbox Code Playgroud)
我发现考虑给定时间点的状态对象是有用的。
这是在我的应用程序中使用的initialState的示例。
const initialState = {
grocers: null,
coords: {
latitude: 37.785,
longitude: -122.406
}
};
Run Code Online (Sandbox Code Playgroud)
这被注入到createStore中。
分解您的应用程序状态对象/属性,应该还可以帮助您简化操作。
考虑分解您的动作。
我的想法,使动作代码脱钩, 在.then 在第二个.then(考虑将结果保存在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
});
}
Run Code Online (Sandbox Code Playgroud)
这是指SOLID设计原则中的S。单一责任原则。
https://devopedia.org/solid-design-principles
如果'getUser'信息获取失败,请考虑一下。
将流程/响应分开将允许更干净地调试应用程序。例如,用户api失败或getTask api失败,等等。
关于redux的更多资源。 https://redux.js.org/introduction/learning-resources#thinking-in-redux
| 归档时间: |
|
| 查看次数: |
285 次 |
| 最近记录: |