简体   繁体   English

如何从React中的另一个函数为componentDidMount设置值?

[英]How can I set value to componentDidMount from another function in React?

I wanted set value to componentDidMount in PeopleItem file from outside function and get return value. 我想从外部函数在PeopleItem文件中将值设置为componentDidMount并获取返回值。 Is this possible? 这可能吗? I am getting error when I executing the program. 执行程序时出现错误。 I started React newly. 我新开始了React。 Can you give me an idea please? 你能给我个主意吗? Thank you in advance.. 先感谢您..

import React from "react";
import axios from "axios";

class PeopleItem extends React.Component {
  async componentDidMount(val) {
    const response = await axios.get(val);
    return response.data;
  }

  _renderObject() {
    const { data } = this.props;
    return Object.entries(data.films).map(([key, value], i) => {
      return <div key={key}>{this.componentDidMount({ value })}</div>;
    });
  }

  render() {
    const { data } = this.props;
    return (
      <div>
        Star Name: {data.name} <br />
        Films:
        {this._renderObject()}
      </div>
    );
  }
}

export default PeopleItem;

You need to study about setState in react. 您需要研究react中的setState。 React work on states. 对状态做出反应。 In your case. 就你而言。 It should be like this : 应该是这样的:

import React from 'react';
import axios from 'axios';

    class PeopleItem extends React.Component{
        state ={
            data:[]
        }
        async componentDidMount() {
            const response = await axios.get(val);
            this.setState({data:response}) //now you can consume it this data in using states
        }

        _renderObject(){
            const {data} = this.props;
            return Object.entries(data.films).map(([key, value], i) => {
                return (
                    <div key={key}>
                        {this.state.data}
                    </div>
                )
            })
        }

        render(){
            const {data} = this.props;
            return (
                    <div>
                        Star Name: {data.name} <br/>
                        Films: 
                        {this._renderObject()}
                    </div>
            );
        }
    }

    export default PeopleItem;

Please explain more about your problem. 请进一步说明您的问题。 I just gave you overview. 我只是给您概述。

From my understanding it should be like this you need to pass value to child component where it fetches data and render it into component : 根据我的理解,应该像这样将值传递给子组件,在子组件中它获取数据并将其呈现为component:

class FetchData extends React.Component {
       async componentDidMount(){
           const response = await axios.get(this.props.val);
           this.setState({ data: response }) 
       }
       render(){
           return(
               <div>
                   Star Name: {data.name} <br />
                   Films:
                        {this.state.data}
               </div>
           )
       }
   }
    class PeopleItem extends React.Component{
        state ={
            data:[]
        }
        async componentDidMount(val) {
             //now you can consume it this data in using states
        }

        _renderObject(){
            const {data} = this.props;
            return Object.entries(data.films).map(([key, value], i) => {
                return (
                    <div key={key}>
                        <FetchData val={val}/>
                    </div>
                )
            })
        }
        fetchData(val){
            const response = await axios.get(val);
            this.setState({ data: response })
        }

        render(){
            return (
                    <div>         
                        {this._renderObject()}
                    </div>
            );
        }
    }

    export default PeopleItem;

Note: This is not an explicit answer to you questions as you need to understand basic concepts of Reactjs. 注意:这不是您对问题的明确答案,因为您需要了解Reactjs的基本概念。

A Reactjs Lifecycle Hook is a 'function' which manipulates the state and this way triggers changes into the dom and only. Reactjs生命周期挂钩是一个操纵状态的“功能”,并且这种方式仅触发dom的更改。

All the variables and functions created inside a lifecycle hook have a short life span and are finished whenever lifecycle hook finishes execution. 在生命周期挂钩中创建的所有变量和函数的寿命很短,并且只要生命周期挂钩完成执行就可以完成。

In your case you have to set all those properties that you intend to access, inside State Object and change them through functions and lifecycle hooks. 对于您的情况,您必须在State Object中设置要访问的所有那些属性,并通过函数和生命周期挂钩对其进行更改。

It doesn't matter if the code is asynchronous or not, as long as it is inside Lifecycle hook it will execute, change the state, and re render component with the new changes. 无论代码是否异步,只要它在Lifecycle挂钩中,它将执行,更改状态并使用新更改重新呈现组件就无关紧要。

Below you have an example: 下面有一个例子:

class sto extends Component {
    state = {
        time: 0
    }

    componentDidMount(){
        //you have no access here from outside
        // when the component mounts it gets the actual date and replaces time property with the actual date
        let date = new Date();
        //async function
        setTimeout(() => {
          this.setState({ date: date });
        }, 5000);
    }

    resetDate = () => {
        // when click event is fired
        // you reset the time property inside state and the change reflects in your component
        this.setState({ time: 0 });
    }

    render() {
        return (
            <div>
                {/* show date */}
                { this.state.date }
                <button onClick = { this.resetDate }>Change Date</button>
            </div>
        );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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