【发布时间】:2017-05-24 15:32:57
【问题描述】:
我正在尝试使用 React-Redux。我有一个连接组件(Coordinates.jsx)嵌套在另一个连接组件(Canvas.jsx)中的情况。
源码https://github.com/RinatRezyapov/Vault-13.git(yarn install 然后yarn start)
在父组件 Canvas.jsx 中,我在 componentDidMount() 中调度一个动作,该动作不可变地改变状态。
Canvas.jsx
componentDidMount() {
this.props.addCanvasSize(windowWidth, windowHeight)
}
问题是在更改状态后,子组件 Coordinates.jsx 没有得到更新,并且 console.log 显示 undefined。
坐标.jsx
componentDidMount() {
console.log(this.props.canvasSize)
}
我确定状态已正确更新(使用 Redux devTool 检查)并且我想我没有在减少状态中改变状态。
如果我将 console.log(this.props.canvasSize) 包装在 setTimeout 中,那么它会显示 coorect 状态。
index.js(商店)
const store = createStore(reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
actions/index.js
export const addCanvasSizeAction = (windowWidth, windowHeight) => ({
type: 'ADD_CANVAS_SIZE',
windowWidth,
windowHeight
})
reducers/reducer.js
export const reducer = (state={}, action) => {
switch (action.type) {
case 'ADD_CANVAS_SIZE':
return Object.assign({}, state, {canvasSize: {canvasWidth: action.windowWidth, canvasHeight: action.windowHeight}})
default:
return state
}
}
components/App.jsx
class App extends React.Component {
render() {
return (
<div>
<CanvasCont />
</div>
)
}
}
components/Canvas.jsx
class Canvas extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
var windowWidth = window.innerWidth-100;
var windowHeight = window.innerHeight-100;
var createCanvas = document.createElement("canvas");
createCanvas.id = 'canvas';
createCanvas.width = windowWidth;
createCanvas.height = windowHeight;
ReactDOM.findDOMNode(this).appendChild(createCanvas);
var rect = canvas.getBoundingClientRect();
var ctx = createCanvas.getContext('2d');
this.props.addCanvasSize(windowWidth, windowHeight)
}
render() {
return (<div>
<CoordinatesCont />
</div>)
}
}
components/Coordinates.jsx
class Coordinates extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
console.log(this.props.canvasSize)
}
render() {
var inlineStyle={
width: "800px",
height: "600px"
}
return (
<div >
<span style={inlineStyle} onMouseMove={this.handleMouseMove}></span>
</div>
)
}
}
容器/CanvasCont.js
const mapStateToProps = (state) => ({
state: state
})
const mapDispatchToProps = (dispatch) => ({
addCanvasSize: (windowWidth, windowHeight) =>
{dispatch(addCanvasSizeAction(windowWidth, windowHeight))}
})
const CanvasCont = connect(
mapStateToProps,
mapDispatchToProps
)(Canvas)
容器/CoordinatesCont.js
const mapStateToProps = (state) => ({
canvasSize: state.canvasSize
})
const mapDispatchToProps = (dispatch) => ({
})
const CoordinatesCont = connect(
mapStateToProps,
mapDispatchToProps
)(Coordinates)
【问题讨论】:
-
请将诊断潜在问题所需的代码放在帖子本身,而不是指向外部存储库。它的连接方式很重要,状态形状很重要。
标签: javascript reactjs redux react-redux