javascript - 如何访问 URL 参数以更新类组件中的组件状态?

标签 javascript reactjs next.js fetch-api

我有一个调用两个 API URL 的 React 组件,现在可以正常进行提取。但我想使用结构类似于 localhost://site/coins/[handle] 的 URL 句柄作为参数来获取不同的数据点。

我计划的方式是使用:

import { useRouter } from 'next/router'
const router = useRouter()

但是我得到一个错误:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

这是我的组件:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      coin: 'bitcoin',
      CoinData: [],
      historicData: [],
      DataisLoaded: false,
    };
  }

  componentDidMount() {
    fetch(
      'https://api.coingecko.com/api/v3/simple/price?ids=' +
        this.state.coin +
        '&vs_currencies=usd&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true&include_last_updated_at=true'
    )
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          CoinData: json,
          DataisLoaded: true,
        });
      });
    fetch(
      'https://api.coingecko.com/api/v3/coins/' +
        this.state.coin +
        '/market_chart?vs_currency=usd&days=3'
    )
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          historicData: json,
        });
      });
  }

  render() {
    const { DataisLoaded, CoinData, historicData, coin } = this.state;

    // console.log(processedData);
    if (!DataisLoaded) return <Skeleton />;

    return (
      <Dashboard>
        <DashboardHeader />
        <DashboardSidebar />
        <Main>
          <TopContainer>
            <div className='topContent'>
              <div role='presentation'>
                <Breadcrumbs aria-label='breadcrumb'>
                  <Link
                    underline='hover'
                    href='/'
                    fontSize='small'
                    fontFamily='Titillium Web'
                    color='#898181'
                  >
                    DefiPlatform
                  </Link>
                  <Link
                    underline='hover'
                    color='#898181'
                    href='/coins/'
                    fontSize='small'
                  >
                    Coins
                  </Link>
                  {/* <Typography color="#fff" fontSize="12px">{router.query.handle}</Typography> */}
                </Breadcrumbs>
              </div>
              <div className='coinMain'>
                <h1>
                  bitcoin
                  <Chip
                    label='BTC'
                    variant='outlined'
                    style={{ color: 'white', borderColor: '#251B55' }}
                  />
                </h1>
                <div>
                  <Chip
                    icon={<LinkIcon style={{ color: '#CECECE' }} />}
                    size='small'
                    label='Bitcoin.org'
                    style={{
                      color: '#CECECE',
                      marginTop: '5px',
                      marginRight: '5px',
                      backgroundColor: '#241E4E',
                    }}
                  />
                  <Chip
                    icon={<ArticleOutlinedIcon style={{ color: '#CECECE' }} />}
                    size='small'
                    label='Whitepaper'
                    style={{
                      color: '#CECECE',
                      marginTop: '5px',
                      marginRight: '5px',
                      backgroundColor: '#241E4E',
                    }}
                  />
                </div>
              </div>
            </div>
            <div className='coinPrice'>
              <div>
                <span className='coin_label'>bitcoin Price (BTC)</span>
                <h2>
                  {CoinData[this.state.coin].usd.toLocaleString('en-US', {
                    maximumFractionDigits: 2,
                  })}{' '}
                  <Ticker Value='1.68%' Variant='BG' />
                </h2>
              </div>
              <div className='coinComparison'>
                <div className='compareData'>12.47 ETH</div>
                <Ticker Value='2%' Variant='outline' />
              </div>
            </div>
          </TopContainer>

          <MainCards>
            <Card>
              <h6>Bitcoin to USD Chart</h6>
              {this.state.coin}
              {JSON.stringify(CoinData[this.state.coin])}
              {JSON.stringify(historicData.prices)}
              {}
            </Card>
            <Card>
              <h6>BTC Price Statistics</h6>
            </Card>
          </MainCards>
        </Main>
      </Dashboard>
    );
  }
}

export default App;

最佳答案

如错误所述,React Hooks 只能在函数组件内部调用。您正在使用类组件,因此您不能调用 useRouter

要访问类组件中的 router 实例,您必须使用 withRouter HOC。然后,您可以从 this.props.router 访问 router

import { withRouter } from 'next/router'

class App extends React.Component {
    // Your `constructor` code here

    componentDidMount() {
        console.log(this.props.router); // Logs the `router` object
        // Remaining code here
    }

    // Your `render` code here
}

export default withRouter(App);

关于javascript - 如何访问 URL 参数以更新类组件中的组件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70528683/

相关文章:

javascript - Next.js 与 Styleguidist 和 Fela (React)

javascript - 如何使用 Scriptacolus 的节点生成器插入 html

javascript - Backbone - 在后端接收DELETE数据

javascript - 如何在 JavaScript 中获取 Tailwind 的事件断点?

javascript - Express 仅提供静态文件

reactjs - 使用react。具有异步获取请求的私有(private)路由器

environment-variables - NextJS - 如何获取运行时环境变量

javascript - tweet.Predicate 指令对 JavaScript 有效,但对 TypeScript 无效

javascript - 更新 div 内的计时器。 JavaScript

reactjs - 在 NextJS 中实现本地相似/不相似功能并使其在客户端路由之间持续存在