如何修改道具传递的值

问题描述 投票:0回答:3

我是React的入门者,想弄清楚如何使用props修改值。

f.e:

我有一个具有@observable值的MobX GameStore.tsx:

export class GameStore {
    @observable money = 0;
    @observable CPS = 0;
    @observable taskCodeLines = 0;
    @observable taskCodeLinesTarget = 10;

...

    @observable staffFrontEndCount = 4;
    @observable staffFrontEndStartCost = 100;

    @observable staffPHPCount = 2;
    @observable staffPHPStartCost = 250;
}

现在我想在Staff类中有一些StaffMember对象:

render() {
    return(
        <div className="staff">
            <ul className="staff-list">
                <StaffMember job="Front End Developer" count={ gameStore.staffFrontEndCount } startCost = { gameStore.staffFrontEndStartCost } />
                <StaffMember job="PHP Developer" count={ gameStore.staffPHPCount } startCost = { gameStore.staffPHPStartCost } />
            </ul>
        </div>
    );
}

我传递了诸如该对象名称和一些值之类的数据。现在我想修改其中一些,例如:

@observer
export default class StaffMember extends React.Component<any, any> {

@computed get increaseStaffCount() {
    return this.props.count;
}


@action hireStaff() {
    let cost = this.props.startCost * 1.4 * (this.props.count + 1);

    if (gameStore.money >= cost) {
        gameStore.money -= cost;

        this.props.count += 1; // It's illegal because props data is read-only
        this.countCPS();
    }


}

我该怎么做?这样创建逻辑可以吗?我应该如何在react中创建类的实例并为其构建通用方法?感谢您的帮助;)

javascript reactjs mobx
3个回答
0
投票

React不允许在组件的使用期限内修改props值。目前,有两种方法可以解决更改道具价值的问题。

  1. 将其加载为状态
  2. 利用Redux

[在第一个项目上,如xSkrappy所述,您可以将道具加载到组件的状态,该状态可以在组件的整个使用过程中进行更新,并通过以下方式在组件内部添加此方法:

componentDidMount() {
    this.setState({ count: this.props.count })
}

这会在组件中创建一个局部状态,该状态等于从其父级传递给该组件的prop值。您可以从那里开始更改它。

[您还可以使用componentWillReceiveProps生命周期方法在其父组件中的props值更改时重新呈现该组件,例如:

componentWillReceiveProps(nextProps) {
    if(nextProps.count !== this.props.count) {
        this.setState({ count: nextProps.count })
    }
}

第二种方法涉及利用Redux,一个可以在React应用程序中使用的状态容器。其模式包括创建一个store,可以在其中管理整个应用程序的状态,任何给定的组件都可以连接到该存储,并以props的形式接收该状态。

虽然使用Redux比给定的第一个选项要复杂得多,但最终,您将获得更大的自由度,因为您可以使您的count值可供应用程序中的任何组件访问!

不幸的是,实现Redux的过程太冗长,无法在此答案中进行详细说明,因此,如果您希望使用此选项,我将引导您到重构应用程序以使用Redux的good guide


0
投票

答案是在将Staff成员内部的道具传递到状态后,然后您可以从那里修改状态:)


0
投票

在ReactJs中,道具是不可变的,因此您无法对其进行修改。除了使用Props,还可以使用StateState可变,您可以对其进行修改。或者,您可以根据需要使用Redux概念。例如:-首先建立一个状态

© www.soinside.com 2019 - 2024. All rights reserved.