【发布时间】:2018-08-23 19:31:45
【问题描述】:
我正在学习如何从头开始实施 redux,但在我的组件重新渲染时遇到了问题。我在 StackOverflow 上搜索此问题 产生了无数结果,其中问题的答案始终是“你改变了你的状态”。我已经阅读了connect 文档,我查看了一堆有类似问题的人,我只是看不出这里的状态突变可能是哪里的问题,所以我将尝试用我的简单示例询问.
这是我的容器组件:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addPokemon } from '../../../redux/actions';
import ReduxTester from '../../components/redux_tester/redux_tester';
export class ReduxTesting extends Component {
constructor(props) {
super(props);
}
addPokemon(name, pokeType) {
addPokemon(name, pokeType);
}
render() {
return (
<div>
<ReduxTester
pokemon={this.props.pokemon}
addPokemon={this.addPokemon}
/>
</div>
);
}
}
const MapStateToProps = function(state) {
return {
pokemon: state.pokemon,
};
};
export default connect(MapStateToProps)(ReduxTesting);
这是我的减速器:
const defaultState = {
pokemon: {},
};
export default function pokemonReducer(state = defaultState, action) {
const newState = Object.assign({}, state);
switch (action.type) {
case 'ADD_POKEMON':
newState.pokemon[action.name] = action.pokeType;
break;
default:
break;
}
return newState;
}
我的具体问题只是 ReactTesting 的 componentWillReceiveProps 方法没有触发,因此组件没有被更新和重新渲染。请注意,mapStateToProps 方法 在调度操作后触发。我知道这是一个如此重复的问题,我的问题不太可能是不同的,但我就是找不到答案。感谢您提供任何帮助。
编辑:为了进一步说明,这里是我的 actions.js,我在其中直接导入了 dispatch 函数:
import { dispatch } from './store';
// Returns an action that fits into the reducer
export function addPokemon(name, pokeType) {
dispatch({
type: 'ADD_POKEMON',
name,
pokeType,
});
}
编辑 2:我找到了一些附加信息,但我不明白。似乎在MapStateToProps 中,当我将整个 Redux 状态分配给一个道具时会触发重新渲染 - 但当我仅将一部分 Redux 状态分配给道具时不会触发。
这会触发重新渲染:
const MapStateToProps = function(state) {
return {
pokemon: state,
};
};
这不是:
const MapStateToProps = function(state) {
return {
pokemon: state.pokemon,
};
};
但我已经确认我的 redux 存储确实具有 pokemon 属性,这就是状态中发生更新的地方。有什么见解吗?
【问题讨论】:
-
你的 componentWillReceiveProps 在哪里?
-
还有你的 mapDispatchToProps 在哪里?
-
查看我的编辑以获取有关我的调度的信息。至于您的其他问题:为简洁起见,我省略了
componentWillReceiveProps。如您所见,我实际上并没有在我的代码中使用它,但我确实事先通过控制台日志语句确认它没有被调用。
标签: reactjs redux react-redux