我对React/Redux不熟悉,对状态有问题.

TrajectContainer.jsx

class TrajectContainer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            trajects: props.trajects,
            onClick: props.onClick
        };
    }

    componentWillReceiveProps(nextProps) {
        console.log('componentWillReceiveProps', nextProps);
        this.setState(nextProps);
    }

    render() {
        // When the componentWillReceiveProps is not present, the this.state will hold the old state
        console.log('rerender', this.state);
        return (<div className="col-md-6">
            <h2>Trajects</h2>
            <button className="btn btn-primary" onClick={this.state.onClick}>Add new Traject</button>
            {this.state.trajects.map(traject => <Traject traject={traject} key={traject.name}/>)}
        </div>)
    }
}

const mapStateToProps = function (store) {
    console.log('mapToStateProps', store);
    return {
        trajects: store.trajects
    };
};

const mapDispatchToProps = function (dispatch, ownProps) {
    return {
        onClick: function () {
            dispatch(addTraject());
        }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(TrajectContainer);

当减速器返回新状态时,组件将使用新数据重新启动.

但是:如果我删除componentWillReceiveProps函数,render()函数将保持旧状态.

我判断了MapStateTops中收到的数据,这是新状态.

我做错什么了吗?

推荐答案

如果你想用新的props 值更新状态值,这个方法将在props 值发生任何变化时被调用.


在您的情况下,为什么需要此组件WillReceiveProps方法?

因为您将props 值存储在状态变量中,并按如下方式使用:

this.state.KeyName

这就是为什么您需要componentWillReceiveProps lifecycle方法来用新的props 值更新状态值,只有组件的props 值会得到更新,但是automatically state will not get updated.如果不更新状态,则this.state将始终具有初始数据.

如果您不在状态中存储props 值并直接使用:

this.props.keyName

现在react将始终在render方法中使用更新的props 值,如果props 发生任何更改,它将使用新props 重新渲染组件.

根据100:

在装入组件之前调用componentWillReceiveProps()

React不调用componentWillReceiveProps和初始props

Suggestion:

不要将props 值存储在状态中,直接使用this.props并创建ui组件.

Reactjs相关问答推荐

webpack 5中动态导入的路径

客户端组件中服务器组件的两难境地

在下一个js中使用ESTAccountWithEmailAndPassword函数时循环

更改滑块标记的文本 colored颜色 ./Reaction/MUI 5

MUiv5和TSS-Reaction SSR问题:无法可靠地处理样式定义.CSSprops 中的ArrowFunctionExpression

在迭代状态时无法读取未定义的属性(读取 map )

Yup.number().integer() 不将 1.0 视为小数,如何解决这个问题?

为什么在 React 的 useEffect 中使用 onAuthStateChanged ?

try 从 React JS 构建此教程游戏但无法继续前进

无法在react 中向表中添加行

React - 使用 React 显示错误和积极alert

如何在不重新加载页面的情况下加载新添加的数据?

未捕获的类型错误:useSelector 不是函数

将 ref 赋予功能组件以使用内部功能

渲染的钩子比预期的少.这可能是由 React Hooks 中意外的提前返回语句引起的

如何跨微前端 React 应用管理状态管理?

为什么 React 会多次调用我的应用程序的某些函数?

React - useParams() 不会失败 null / undefined 判断

如何在组件文件夹内的react 组件文件中导入外部css文件?

我想将悬停 colored颜色 更改为红色.写了一个话题,这个元素没有react ,怎么解决呢?