简体   繁体   中英

Update variable in React in class not extending component

I am trying to wrap my head around ReactJS and I am stumped with an issue where I want to be able to update the value of a local variable and return the updated value.

I've read about state and I've used that when working with React Components, however, this class is just defined as const and it doesn't extend React.Component.

Is there a different way I should be defining setting the variable?

Here is a simplified version of my code:

 import React from 'react'; const WelcomeForm = ({welcome}) => { var welcomeMsg = 'Test'; DynamicContentApi.loadDynamicContent('welcome_test').then((response) => { // response.text has content welcomeMsg = response.text; }).catch(() => { welcomeMsg = ''; }); return ( <p>{welcomeMsg}</p> // Returns 'Test' ); }; export default WelcomeForm; 

The easiest option here is to change your stateless component to a stateful component .

Stateless components are just JavaScript functions. They take in an optional input, called prop.

Stateful components offer more features, and with more features comes more baggage. The primary reason to choose class components (stateful) over functional components (stateless) is that they can have state , that is what you want to update to re-render.

Here is what you can do:

class WelcomeForm extends React.Component {
  state = {
    welcomeMsg: ''
  }
  fetchFromApi() {
    DynamicContentApi.loadDynamicContent("welcome_test")
    .then(response => {
      this.setState({welcomeMsg: response.text});
    })
    .catch((e) => console.log(e));
  }
  componentDidMount() {
    fetchFromApi();
  }
  render() {
    return (
      <p>{welcomeMsg}</p>
    );
  }
};

If you want, for any reason, to keep your component stateless , you will have to put the loadDynamicContent() function on the Parent and pass the text to WelcomeForm as a prop. For example:

// Your WelcomeForm Component
const WelcomeForm = ({welcomeMsg}) => (
  <p>{welcomeMsg}</p>
);

// Whatever it's Parent Component is
class Parent extends React.Component {
  state = {
    welcomeMsg: ''
  }
  fetchFromApi() {
    DynamicContentApi.loadDynamicContent("welcome_test")
    .then(response => {
      // response.text has content
      this.setState({welcomeMsg: response.text});
    })
    .catch((e) => console.log(e));
  }
  componentDidMount() {
    fetchFromApi();
  }
  render() {
    <WelcomeForm welcomeMsg={this.state.welcomeMsg} />
  }
}

As suggested in the comments, you can pass the DynamicContentApi logic to outside:

import ReactDOM from 'react-dom'

DynamicContentApi.loadDynamicContent('welcome_test').then((response) => {
  ReactDOM.render(<WelcomeForm data={response.text} />, document.getElementById('where you wanna render this'));
}).catch(() => {
  console.log('error while fetching...');
});

And where you have your component:

import React from 'react';

export default class WelcomeForm extends React.Component {
  render() {
    return (
      <p>{this.props.data}</p>
    );
  }
}

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