0

我有一个名为 [id].js 的页面

该页面有一个获取博客文章 id 的函数:

function BlogPost() {
  const router = useRouter()
  const blogId = router.query.id
}

而且它还有一个 react 组件,需要从这个函数中取值来获取数据。该变量位于获取请求 URL 中。

class Home extends React.Component {
    state = {
      post: {},
      isLoaded: false
    };
    componentDidMount() {
      fetch(`http://localhost/wordpress/index.php/wp-json/wp/v2/featured_item/${blogId}`)
        .then(postsResponse => postsResponse.json())
        .then((post) => {
          this.setState({
            post,
            isLoaded: true
          })
        })
    }
    render() {
      const { post, isLoaded } = this.state;
      if(isLoaded){
      return (

        <motion.div initial="initial" animate="enter" exit="exit" variants={portfolioVariants}>
          <Posts post={post}/>
        </motion.div>
      )
        }else{
        return(
          <Loader />
        )
        }


    }
  }

如果我把实际的博客文章 ID 放在获取 URL 的末尾,说“33”,它可以正常工作,但是如果我把 BlogPost() 函数中的一个变量放在那里,它会说“没有定义 blogId”。

所以问题是:如何将这个变量传递给组件?

UPD

我按照评论中的建议做了,它只是给出了同样的错误。也许我做错了什么。

class Home extends React.Component {
    state = {
      post: {},
      isLoaded: false,
      id: blogId
    };
    componentDidMount(blogId) {
      fetch(`http://localhost/wordpress/index.php/wp-json/wp/v2/featured_item/${this.state.id}`)
4

4 回答 4

0

我相信您是从道具中获取 blogId 的,请确认?

在这种情况下:

componentDidMount() {
      fetch(`http://localhost/wordpress/index.php/wp-json/wp/v2/featured_item/${this.props.blogId}`)
        .then(postsResponse => postsResponse.json())
        .then((post) => {
          this.setState({
            post,
            isLoaded: true
          })
        })
    }
于 2019-10-19T09:02:54.430 回答
0

useRouter- 是一个钩子。您的Home组件 - 是一个类组件。您不能在类组件中使用钩子,只能在功能中使用。因此,如果您需要从类组件中的查询字符串中获取一些查询参数(id在您的情况下),您必须Home使用withRouterHOC 包装您的:

import { withRouter } from "react-router";

... 
export default withRouter(Home);

然后您将可以访问路由器数据。

如果你使用 react-router v3,那么你可以得到id这样的结果:

const {id} = this.props.location.query;

如果您使用反应路由器 v4 或 v5。您必须安装一些 URL 解析器,如查询字符串并自行解析location

import qs from `query-string`;

....

const { id }  = qs.parse(this.props.location.search);
于 2019-10-19T09:24:12.313 回答
0

尝试blogId从函数返回:

function BlogPost() {
  const router = useRouter()
  const blogId = router.query.id
  return blogId
}

然后调用BlogPost()函数fetch

fetch(`http://localhost/wordpress/index.php/wp-json/wp/v2/featured_item/${BlogPost()}`)
于 2019-10-19T09:20:22.033 回答
0

函数变量无法从函数中访问,因此您需要使用状态在组件范围内的任何位置获取此数据,或者将您的 id 存储在“this”引用中,如 this.id =“your id”

BlogPost=()=> {
 const router = useRouter()
 this.setState({id: router.query.id })
}

现在 fetch url 会像这样

fetch(`http://localhost/wordpress/index.php/wpjson/wp/v2/featured_item/${this.state.id}`)
于 2019-10-19T08:47:52.253 回答