admin管理员组

文章数量:1312960

sorry if this question appeared somewhere else, but it's getting extremely frustrating to find answers where every question involves event handler or child element method calling.

I need to call a function when ponent is initialized, basically when window loads, or instantly.

On initialization I want to call a getGameMeta() to update Game state, if I'm trying to call it in jsx either I make a loop or get an error saying "Functions are not valid as a React child. This may happen if you return a Component instead of from render...."

class Game extends React.Component{
constructor(props) {
    super(props);
    this.state = {name: undefined,};
    this.getGameMeta = this.getGameMeta.bind(this);
}

getGameMeta(){
    fetch(Url).then(data => {
        console.log(data);
        this.setState({
            name: data[0].name
        });
    });
};

render(){
    return (
    <div>
        {/* {this.getGameMeta()} */} causes loop
        {/* {this.getGameMeta} */} causes error
        <p>{this.state.name}</p>
    </div>
    );
  };
};

sorry if this question appeared somewhere else, but it's getting extremely frustrating to find answers where every question involves event handler or child element method calling.

I need to call a function when ponent is initialized, basically when window loads, or instantly.

On initialization I want to call a getGameMeta() to update Game state, if I'm trying to call it in jsx either I make a loop or get an error saying "Functions are not valid as a React child. This may happen if you return a Component instead of from render...."

class Game extends React.Component{
constructor(props) {
    super(props);
    this.state = {name: undefined,};
    this.getGameMeta = this.getGameMeta.bind(this);
}

getGameMeta(){
    fetch(Url).then(data => {
        console.log(data);
        this.setState({
            name: data[0].name
        });
    });
};

render(){
    return (
    <div>
        {/* {this.getGameMeta()} */} causes loop
        {/* {this.getGameMeta} */} causes error
        <p>{this.state.name}</p>
    </div>
    );
  };
};
Share Improve this question asked Jul 26, 2018 at 19:01 EfkissEfkiss 1154 silver badges11 bronze badges 2
  • 1 What about ponentDidMount? – The Reason Commented Jul 26, 2018 at 19:03
  • 1 use lifecycle hook else any update to ponent will render it again and again calling getGameMeta. Use lifecycle method by @TheReason – simbathesailor Commented Jul 26, 2018 at 19:05
Add a ment  | 

3 Answers 3

Reset to default 4

Using the ponentDidMount hook is a great way to load data from a remote endpoint when the ponent is first mounted.

Example

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: undefined };
    this.getGameMeta = this.getGameMeta.bind(this);
  }

  ponentDidMount() {
    this.getGameMeta();
  }

  getGameMeta() {
    fetch(Url).then(data => {
      console.log(data);
      this.setState({
        name: data[0].name
      });
    });
  }

  render() {
    return (
      <div>
        <p>{this.state.name}</p>
      </div>
    );
  }
}

You can call it in ponentDidMount. It guarantees that it will be called once and right after when ponent will be mounted. More over from React Docs:

If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

getGameMeta(){
    fetch(Url).then(data => {
        console.log(data);
        this.setState({
            name: data[0].name
        });
    });
};

ponentDidMount(){ this.getGameMeta() }

So seems like this is the way you are looking for

You can simply use useEffect if you are using a functional ponent. basically, it loads the data before rendering your UI.

import {useEffect} from "react";
const GameData=()=>{
const [fetchD,setFetchD]=useState("");
 useEffect(()=>{
     fetch(Url).then(data => {
    console.log(data);
    setFetchD(data[0].name);
    });
});
 })
}
export default GameData;

//you can also check react documentation at https://reactjs/docs/hooks-effect.html

本文标签: javascriptCall a function in react componentWITHOUT event handlers or propsStack Overflow