简体   繁体   中英

How can I ensure that a React component's state is correct?

I'm building a desktop application with Electron and React and would like to know the best way to validate a component's state or whether there is a better approach to this.

Scenario

Suppose that you have a subscription-based application that will display content depending on the user's subscription status. The first thing a new user sees is a sign in box. When successfully signing in, the application will fetch the user's subscription status from the database. If the user is subscribed, they will see premium content. If they are not subscribed, they will see free content.

A simple example of how the components may look is as follows:

Interface.js

class Interface extends React.Component {
    constructor() {
        super();

        this.state = {
            signedIn: false,
            hasSubscription: false
            // ...
        }
    }

    // ...

    handleSignIn = (username, password) => {
        // ...

        this.setState({
            // signedIn: true | false
            // hasSubscription: true | false
        });
    };

    render() {
        const display = (this.state.signedIn) ? 
            <Content subscribed={this.state.hasSubscription}/> : <SignIn handleSignIn={this.handleSignIn}/>;

        return (
            {display}
        );
    }
}

SignIn.js

class SignIn extends React.Component {
    handleSubmit = (username, password) => {
        this.props.handleSignIn(username, password);
    };

    render() {
        return (
            // ...
        );
    }
}

Content.js

class Content extends React.Component {
    // ...
}

Problem

The problem with this is that the user may obtain subscription-only content by changing the state of hasSubscription in the Interface component.

Question

How can this problem be solved so that the state of the Interface component is accurate?

From a security perspective, in general, you should never trust browser-side JavaScript to tell you the truth, unless the server can verify it (precisely for the reason you have discovered - it can easily be tampered with). So, your server should not return any data to the client that the server itself cannot verify that the user should have access to. How you accomplish that depends on a lot of things in your tech stack. It sounds like you're already doing authentication and storing user permission levels in a database, so you should have your server perform the appropriate checks any time it returns data to the client application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM