我的团队正在研究 我们从Themeforest购买React Isomorphic主题,它捆绑了Redux,Saga和React Router V.4。我们正在努力解决它。 我一直在使用React一段时间,但对Redux来说是新手,并且从未体验过这种行为。问题在于,每当我调度一个动作时,组件都会在状态发生变化时卸载并重新安装 好的,我正在做的是从API获取一些用户数据但是。这就是我如何提出以下行动&减速器 和减速器 使用Redux Saga,可以创建中间件来处理异步操作。这就是它的外观 现在我在我的组件中实现代码,就像这样 现在你可以看到,之前提到的行为。通过this.props.fetchUser()调度一个动作会导致状态发生变化,但我不能指望的是该组件不应该卸载并重新安装,因为一旦它这样做,就会发生无限循环,因为componentDidMount反复运行,状态也相应改变。 我期望的是,一旦组件安装完毕,一旦状态发生变化,就会从API中获取数据,因为我们购买的主题配备了其他基本组件,这些组件利用Redux-saga来处理状态和异步操作。例如,可折叠侧边栏触发一个调度,一旦用户点击它就会改变控制其行为的状态。目前,一旦这样做,我的当前组件会立即意外卸载。 有没有办法解决这样的问题,或者这是Redux的默认行为?// Actions.js
const UserActions = {
FETCH_USER_REQUEST: 'FETCH_USER_REQUEST',
FETCH_USER_SUCCESS: 'FETCH_USER_SUCCESS',
fetch_users: () => {
return {
type: UserActions.FETCH_USER_REQUEST
}
}
}
export default UserActions;
// Reducer.js
export default function UserReducer(state = initialState, action) {
switch (action.type) {
case 'REQUEST_USER_SUCCESS':
return state.set('user_list', action.user_list);
default:
return state;
}
}
// Saga.js
import { all, takeEvery, call, put, fork } from 'redux-saga/effects';
import {get, post} from 'axios';
export function fetchUser() {
return get('https://mockapi.testapp.dev/users')
.then(response => {
return response.data;
}).catch(error => {
return error.data
});
}
export function* fetchUserRequest() {
yield takeEvery('FETCH_USER_REQUEST', function*() {
const resp = yield call(fetchUser);
yield put({
action: 'FETCH_USER_SUCCESS',
user_list: resp
});
});
}
export default function* rootSaga() {
yield all([
fork(fetchUserRequest)
]);
}
// App.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import UserActions from './actions/UserAction';
const mapStateToProps = (state, ownProps) => {
return {
userList: state.User.get('user_list')
}
}
const mapDispatchToProps = dispatch => {
return {
fetchUser: () => dispatch(UserActions.fetch_users())
}
}
class App extends Component {
componentDidMount() {
this.props.fetchUser();
}
render() {
// ... The rest of the rendering processes
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);