【问题标题】:How do I change an id to a slug for the URL using React Router DOM如何使用 React Router DOM 将 id 更改为 URL 的 slug
【发布时间】:2018-08-11 01:53:42
【问题描述】:

我正在使用一个 API,我可以在其中使用帖子 ID 进行搜索。如何将链接更改为我创建的 slug。 Ex 而不是/posts/1,它将成为posts/slugtitle

Post.js

componentDidMount() {
  const { match: { params } } = this.props;
  axios
    .get(`/api/posts/${params.postId}`)
    .then(response => {
      console.log(response);
      this.setState({ post: response.data });
    })
    .catch(error => console.log(error));
}

Routes.js

<Route path={"/post/:postId"}  strict component={PostShow} />

另外,如果没有搜索到的 id 的帖子,最简单的重定向方法是什么?

【问题讨论】:

  • 蛞蝓从哪里来?您对 axios 的回应?
  • 我不太确定我是否理解您想要实现的目标。要重定向,您可以使用将出现在 PostShow 道具中的 history 对象。 this.props.history.push('/somepath');this.props.history.replace('/somepath');
  • 是的,slug 在 axios 的响应中。

标签: reactjs react-router-dom


【解决方案1】:

更改代码中的某些内容,您必须知道,女巫参数是否传递了 init,也许您想传递 title 或 id,我给您举个例子,
我们需要的是一个知道我们是title或id的状态, 所以添加这个状态:

constructor(props) {
    super(props);
    this.state = {
        passTitle: false,
        title:"",
        id:0
    }
}

现在您必须在单击标题时更改此状态,(想象一下,当用户单击标题时,更改路径,标题,否则,更改 id 上的路径:

handleTitleClick=(title)=>{
   this.setState({title:title,passTitle:true});
}

handleNotTitleClick=(id)=>{
   this.setState({id:id,passTitle:false});
}

将您的 componentDidMount 更改为函数:

runPost=()=>{
   const { match: { params } } = this.props;
     const {passTitle,title,id}=this.state
     axios
        .get(`/api/posts/${passTitle?title:id}`)
        .then(response => {
          console.log(response);
          this.setState({ post: response.data });
        })
         .catch(error => console.log(error));
   }  

然后在 this.setState 之后运行它:

handleTitleClick=(title)=>{
   this.setState({title:title,passTitle:true},()=>{this.runPost()});
}

handleNotTitleClick=(id)=>{
   this.setState({id:id,passTitle:false},()=>{this.runPost()});
}

【讨论】:

    猜你喜欢
    • 2021-03-19
    • 2018-12-22
    • 1970-01-01
    • 2021-01-09
    • 2018-01-24
    • 1970-01-01
    • 2018-12-08
    • 2021-07-02
    • 2018-04-23
    相关资源
    最近更新 更多