【发布时间】:2020-03-04 16:30:13
【问题描述】:
由于 how data flows 通过 React-Redux 应用程序,在 React 组件重新渲染之前,在商店中更新的数据不可用。
我的问题是,在给定组件中,我想使用更新后的商店 重新渲染组件。我想做这样的事情:
import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import * as AActions from "../aactions";
import * as BActions from "../bactions";
import * as CActions from "../cactions";
class MyComponent extends Component<Props>{
constructor(props){
super(props);
this.func = this.func.bind(this);
};
func(){
// Add item to A
this.props.addAItem("value");
// Get id of newly added item in A
let addedA = this.props.A.find(a => a.name === "value");
// Insert new items in B with the id of A
this.props.addBItem(addedA.id, "valueB");
// etc...
}
render(){
<div onClick={() => this.func()}>click me</div>
}
}
function mapStateToProps(state, props){
return {
A: state.A,
B: state.B,
C: state.C
};
}
function mapDispatchToProps(dispatch){
return bindActionCreators({...AActions, ...BActions, ...CActions}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
这不起作用,因为 props 在 MyComponent 重新渲染之前不会更新。我不能打电话给this.props.A.find(a => a.name === "value");,因为道具不会有最近添加的“A”值。就我而言,我等不及 MyComponent 重新渲染。在 MyComponent 中访问最新状态的选项有哪些?
我做过类似的事情,但它绝对是可怕的,但它确实有效......
func(){
if (this.props.step1){
// Add item to A
this.props.addAItem("value");
this.props.setStep2();
} else if (this.props.step2) {
// Get id of newly added item in A
let addedA = this.props.A.find(a => a.name === "value");
this.props.setStep3();
}
// etc...
}
【问题讨论】:
-
我不明白这个问题。 - 当 redux store 更新时,你的组件的 props 会发生变化,并且会发生重新渲染(假设你没有实现 shouldCompoentUpdate 方法)。为什么要在不重新渲染的情况下更改组件的内部状态?
-
@dwjohnston 这种思维模式背后的原因是所有动作都应该作为一个单元发生,我不能让 MyComponent 重新渲染,因为这样做需要我点击那个再次。我需要对状态进行多次更改(取出最近插入元素的 id)。组件重新渲染不会重置组件状态。只需在onclick上设置组件状态,然后dispatch?@dwjohnston 我的组件依赖于商店的价值。 store 的值(映射为 props)在组件接收到新的 props(并且组件被重新渲染)之前不会更新。除了我的函数需要用户输入外,一切都可以正常工作,所以在我调用第一次调度后,组件重新渲染并且我的 func() 不会继续执行,这有意义吗?
标签: reactjs redux react-redux