【问题标题】:How to access state from a react function component?如何从反应功能组件访问状态?
【发布时间】:2022-11-21 14:19:26
【问题描述】:

基本上我正在使用 react-router(版本 5)来传递数据,但是我无法访问我传递的状态。这是它路由的代码:

export default function MarketsList(props) {
  const history = useHistory();
  function changePage(sym, id) {
    history.push({ pathname: `/${sym}`, state: { id: id } })
  }

我如何从其他页面访问它?我试过 this.state.id 但它不起作用。 这是另一页的代码,以防万一。

export default function Symgraph(props) {
  useEffect(() => {

  }, []);
  const { sym} = useParams();
  return (
    <div className='main-chart mb15' >
      <ThemeConsumer>
        {({ data }) => {
          return data.theme === 'light' ? (
            <AdvancedChart
              widgetProps={{
                theme: 'light',
                symbol: 'OKBUSDT',
                allow_symbol_change: false,
                toolbar_bg: '#fff',
                height: 550,
                details: 'true',
                style: '3',
              }}
            />
          ) : (
            <AdvancedChart
              widgetProps={{
                theme: 'dark',
                symbol: 'OKBUSDT',
                allow_symbol_change: false,
                toolbar_bg: '#000',
                height: 550,
                details: 'true',
                style: '3',
              }}
            />
          );
        }}
      </ThemeConsumer>

      <h1>{sym},{this.state.id}</h1>
    </div>
  )
}

【问题讨论】:

标签: javascript reactjs react-hooks react-router


【解决方案1】:

我认为您需要为此使用 useHistory

像这样:

  let history = useHistory();

history.location?.state?.id

【讨论】:

    【解决方案2】:
    import { useHistory, useLocation } from 'react-router';
    const Component = ()=>{
     const location = useLocation();
     console.log(location.state.id);  // here you can access id;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2021-01-24
      相关资源
      最近更新 更多