reactjs 如何从React函数组件访问状态?[duplicate]

6vl6ewon  于 2022-11-22  发布在  React
关注(0)|答案(2)|浏览(142)

此问题在此处已有答案

How to pass data from a page to another page using react router(5个答案)
昨天关门了。
基本上我使用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>
  )
}
vbkedwbf

vbkedwbf1#

我认为您需要为此使用useHistory
这样的东西:

let history = useHistory();

history.location?.state?.id
u2nhd7ah

u2nhd7ah2#

import { useHistory, useLocation } from 'react-router';
const Component = ()=>{
 const location = useLocation();
 console.log(location.state.id);  // here you can access id;
}

相关问题