React: How to wait data before using "this.state.x" into a function?

Asked
Active3 hr before
Viewed126 times

7 Answers

functionstateusingreact
90%

GitLab launches Collective on Stack Overflow , Stack Overflow Public questions & answers , Meta Stack Overflow ,Thanks for contributing an answer to Stack Overflow!

You're going to need to conditionally render. Provide a loading state to be loaded prior to asynchronously required data. You'll want something like the following:

class WrapperComponent extends PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            isLoaded: false,
            data: null
        };
    }

    componentDidMount() {
        MyApiCall.then(
            res => this.setState({
                // using spread operator, you will need transform-object-rest-spread from babel or
                // another transpiler to use this
                ...this.state, // spreading in state for future proofing
                isLoaded: true,
                data: res.data
            })
        );
    }

    render() {
        const { isLoaded, data } = this.state;
        return (
            {
                isLoaded ?
                    <PresentaionComponentThatRequiresAsyncData data={ data } /> :
                    <LoadingSpinner /> // or whatever loading state you want, could be null
            }
        );
    }
}
load more v
88%

This function results in request data like the following:,then take a look at the answers to this question:,In both cases, it's converted to the standard string representation used by form data.,The end result is data like this in the form_data variable:

I have a simple component which renders this (note that it renders a li array thanks to function getSlots):

render () {
    return (
        <ul>
          {this.getSlots(this.state.viewing).map(item => <li key={item}>{item}</li>)}
        </ul>
    )
  }

Function getSlots is:

constructor(props) {
   ...
}

getSlots(viewing) {

   SOME STUFF...

      const monday = this.state.house.monday

   return SOME STUFF...
}

componentDidMount() {
   ...
}

render() {
   ...
}
load more v
72%

关于javascript - react : How to wait data before using "this.state.x" into a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47850047/

我目前正在学习 React,有些东西对新手来说并不那么容易......

我有一个简单的 renders 组件(注意,由于 函数 li ,它呈现了一个 getSlots 数组):

render () {
    return (
        <ul>
          {this.getSlots(this.state.viewing).map(item => <li key={item}>{item}</li>)}
        </ul>
    )
  }
load more v
65%

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />      <Welcome name="Cahal" />      <Welcome name="Edite" />    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
load more v
75%

Let’s look through again how withMousePosition and withWindowScroll are nested among codes used in the above:,Components that are returned through the withWindowScroll function are injected with x, y as props. However, what about using a nested HOC that injects props in the same name? For example, let’s assume the use of the HOC named withMousePosition, which injects the mouse location in the name of x, y, as below.,Supporting this with the withWindowScroll function is not difficult: wrap the logic which returned existing components with the function once again.,Now, let’s modify the withWindowScroll function more, so as to support the mapProps function.

Let’s start with a simple exercise. I want to create a component that shows the location of windows scroll every time it changes. To this end, an event handler of scroll of window must be registered and unregistered, each when the component is mounted and unmounted.

class WindowScrollTracker extends React.Component {  state = {    x: 0,    y: 0  }  scrollHandler = () => {    this.setState({      x: window.pageXOffset,      y: window.pageYOffset    });  };  componentDidMount() {    window.addEventListener('scroll', this.scrollHandler);  }    componentWillUnmount() {    window.addEventListener('scroll', this.scrollHandler);  }  render() {    return (      <div>        X: {this.state.x},        Y: {this.state.y}      </div>    );  }}
load more v
40%

D3 is great. As the jQuery of the web data visualization world, it can do everything you can think of.,Many of the best data visualizations you’ve seen online use D3. It’s a great library, and with the recent v4 update, it became more robust than ever.,Now we’re ready for the cool stuff — a component that can transition itself into and out of a visualization declaratively.,Just like jQuery, D3 is powerful but low level. The bigger your visualization, the harder your code becomes to work with, the more time you spend fixing bugs and pulling your hair out.

Try to guess what this code does:

render() {
  // ...
  return (
    <g transform={translate}>
      <Histogram data={this.props.data}
         value={(d) => d.base_salary}
         x={0}
         y={0}
         width={400}
         height={200}
         title="All" />
      <Histogram data={engineerData}
         value={(d) => d.base_salary}
         x={450}
         y={0}
         width={400}
         height={200}
         title="Engineer" />
      <Histogram data={programmerData}
         value={(d) => d.base_salary}
         x={0}
         y={220}
         width={400}
         height={200}
         title="Programmer"/>
      <Histogram data={developerData}
         value={(d) => d.base_salary}
         x={450}
         y={220}
         width={400}
         height={200}
         title="Developer" />
    </g>
  )
}

load more v
22%

For React Apollo, I use setTimeout and wrapper.update() in every it function to wait for data fetched from my local database before starting assertion:,Your test has 2 renders - one from the setState, and another one because you call update() The production flow only has 1.,What's react-apollo, and what test utils would you be trying to use with enzyme?,Calling setState as part of the test, or for that matter .update, will cause an additional render, that's isn't there in production scenario

const wrapper = mount(
<Component />);
triggerAction();

// wrapper.update() could be necassary
// https://github.com/airbnb/enzyme/blob/master/docs/api/mount.md#update--reactwrapper

// inspect expected changes in wrapper
expect(wrapper.find('.updatedElement')).toBe('span')
load more v

Other "function-state" queries related to "React: How to wait data before using "this.state.x" into a function?"