简体   繁体   中英

How to pass data between React components without rendering the child component

I'm trying to get data from my textService into the Error500Page without rendering the Error500Page. How can you pass state data as props without rendering the child component?

I'm trying to do this but it doesn't seem to work very well.

This is my code in the parent class


 constructor(props){
    super(props);
    this.state = {
      url:"",
      data: [],
      isLoaded: false,
      test: "Will it work?",
    }
  }

  componentDidMount() {
    this.fetchImg(process.env.REACT_APP_TEXT_API);
    this.passError500();
  }


  fetchImg(url){
    const proxyurl = "https://cors-anywhere.herokuapp.com/";
    fetch(proxyurl+url)
      .then(res => res.json())
      .then(json => {
        this.setState({
          isLoaded:true,
          data:json,
          test: "Will it work?",
        })
      })

  }
  passError500(){
    return(
      <Error500Page test={this.state.test}/>
      )

  }


And this is how I try to access the props in the child class

import TextService from 'src/app/services/textService/textService';

const Error500Page = (props) =>
{

  console.log(props.test);
    return (
        <div className="flex flex-col flex-1 items-center justify-center p-16">

            <div className="max-w-512 text-center">

                <FuseAnimate animation="transition.expandIn" delay={100}>
                    <Typography variant="h1" color="inherit" className="font-medium mb-16">
                      {props.test}
                    </Typography>
                </FuseAnimate>

When I console log props.test I get undefined. Any idea how can I make this work? Thanks

尝试使用this.props访问道具

const Error500Page = (this.props) =>

Maybe you'll get what you want with this:

 export function Error500Page(test) { return <div className="flex flex-col flex-1 items-center justify-center p-16"> <div className="max-w-512 text-center"> <FuseAnimate animation="transition.expandIn" delay={100}> <Typography variant="h1" color="inherit" className="font-medium mb-16"> {test} </Typography> </FuseAnimate>; } export default { Error500Page };

 passError500(){
    return(
     Error500Page(this.state.test)
      )

  }

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