S
S
sharkdest2018-10-12 16:42:15
JavaScript
sharkdest, 2018-10-12 16:42:15

How to enforce two way communication between components in ReactJS?

Hello, I
have a class and a function:

import React from 'react';

export default class ResultsContainer extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      //хочу получить в state ответ с myFunction
      response: ''
    };
  }

  componentDidMount = () => {
    const a=1;
    myFunction(a);
  }

  render() {
    return (
      <div>
      ...
      </div>
    )
  }
}

const myFunction = (props) => {
  const {a} = props;
  const response = a++
    return (
      response
    )
}

How to pass a variable from a class to a function and then pass the response from the function to the state of the class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-10-12
@sharkdest

1. Declaring componentDidMount as an arrow function is insanity. It doesn't make any sense.
2. If your function is executed synchronously, it is enough to reduce to:

const response = myFunction(1);
this.setState({ response });

3. If asynchronous:
componentDidMount() {
  const { someValue } = this.props;
  // асинхронный вызов, возвращающий Promise
  fetchSomeData(someValue).then(response => this.setState({ response }));
}

or:
async componentDidMount() {
  const { someValue } = this.props;
  // асинхронный вызов, возвращающий Promise
  const response = await fetchSomeData(someValue);

  this.setState({ response }));
}

4. The myFunction function itself is written very poorly and contains an error. It is better:
const myFunction = num => ++num;

A
Alexey Ukolov, 2018-10-12
@alexey-m-ukolov

componentDidMount = () => {
    const a=1;
    this.setState({response: myFunction(a)});
}

If the function is asynchronous:
async componentDidMount = () => {
    const a=1;
    this.setState({response: await myFunction(a)});
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question