如何在React组件之间传递数据而不渲染子组件

时间:2019-08-28 14:22:12

标签: javascript reactjs react-props

我正在尝试将我的textService中的数据获取到Error500Page中,而不呈现Error500Page。如何在不渲染子组件的情况下将状态数据作为道具传递?

我正在尝试执行此操作,但效果似乎不太好。

这是我在父类中的代码


 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}/>
      )

  }


这就是我尝试访问子类中道具的方法

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>

当我控制台记录props.test时,我不确定。你知道我该怎么做吗?谢谢

2 个答案:

答案 0 :(得分:0)

尝试使用this.props

访问道具
const Error500Page = (this.props) =>

答案 1 :(得分:0)

也许您会得到想要的东西:

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)
      )

  }