首先,我想说的是我已经阅读了有关该主题的内容,但我仍然无法理解正在发生的事情,因此,如果有重复之处,请提前抱歉。从componentDidMount上的服务器中获取数据的组件,但它以某种方式进入了无限循环。我正在使用react router和redux saga,并且该组件的父级也已连接到redux存储(我认为这是问题所在)。
App.js呈现方法:
render() {
console.log(this.props.isAuthenticated);
let routes = (
<Switch>
<Route path="/login" component={Login} />
<Route path="/" exact component={Home} />
<Redirect to="/" />
</Switch>
);
if (this.props.isAuthenticated) {
routes = (
<Switch>
<Route path='/logout' component={Logout} />
<Route path='/data/people' component={People} />
<Route path="/" exact component={Home} />
<Redirect to="/" />
</Switch>
)
}
return (
<div>
<Layout>
{routes}
</Layout>
</div>
);
}
调用以获取数据(在People.js中调用):
componentDidMount() {
this.props.fetchPeople()
}
App.js Redux连接:
const mapStateToProps = state => {
return {
isAuthenticated: state.login.token !== null,
username: state.login.username
};
};
const mapDispatchToProps = dispatch => {
return {
autoLogin: () => dispatch(actions.checkLoginState())
}
};`
People.js redux连接:
const mapStateToProps = state => {
return {
people: state.data.people,
loading: state.data.loading
};
};
const mapDispatchToProps = dispatch => {
return {
fetchPeople: () => dispatch(actions.fetchPeople())
};
};
actions.fetchPeople称之为传奇:
export function* fetchPeopleSaga () {
try {
yield put(actions.fetchPeopleStart());
const people = yield axios.get('/data/people');
yield put(actions.fetchPeopleSuccess(people));
} catch (error) {
yield put(actions.fetchPeopleFail(error));
}
};
这是相关的减速器:
const initialState = {
people: null,
error: null,
loading: false
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.FETCH_PEOPLE_START:
return {
...state,
loading: true
}
case actionTypes.FETCH_PEOPLE_SUCCESS:
return {
...state,
people: action.people,
loading: false
}
case actionTypes.FETCH_PEOPLE_FAIL:
return {
...state,
people: null,
error: action.error,
loading: false
}
default:
return state
}
};
如您所见,他们甚至没有使用相同的道具,所以我不明白为什么它会进入无限渲染。
我们将不胜感激!
答案 0 :(得分:1)
您可以添加其他状态loaded
并将其设置为true(如果是FETCH_PEOPLE_SUCCESS
或FETCH_PEOPLE_FAIL
)。然后,在获取人员数据之前添加对已加载和正在加载的检查,例如:
if (!loaded && !loading) {
this.props.fetchPeople()
}
答案 1 :(得分:0)
ComponentDidMount将被调用一次,除非您再次重定向到该页面。 请检查,您必须一次又一次地在该页面/组件上进行重定向。