【问题标题】:Reactjs share link to state controlled pageReactjs 共享链接到状态控制页面
【发布时间】:2019-08-03 02:45:01
【问题描述】:

我有一个使用 react route version 4 和 react16.3 的 reactjs 项目。我可以导航到页面http://localhost:8000/#/my-list,它将带您到 MyList 组件,在我的列表组件上,有一个链接可以查看单个列表,该列表的行为类似于 SPA,通过如下更改状态。

import React,{Component} from 'react'

class MyList extends Component{
     constructor(props){
         super(props)
         this.state={
            canViewItem:false
         }
         this.viewItem=this.viewItem.bind(this)
     }

     viewItem(){
          this.setState({canViewItem:true})
     }
 renderDisplay() {
        const {canViewItem}=this.state
         if(canViewOrder){
            return <canViewItem cancel={this.cancel} item={item}  />
        }
        else {
            return this.renderMyList()
        }
    }

     renderMyList(){
        return(
                <table>
                    <thead>
                         <tr>
                            <th>Iten Name</th>
                            <th>Quantity</th>
                            <th>More Details</th>
                         </tr>                                 
                     </thead>
                     <tbody>                                 
                          <tr>
                              <td>Item 1</td>
                               <td>10</td>
                               <td>onClick={() => this.viewItem(item1Obj)}</td>
                          </tr>
                          <tr>
                              <td>Item 2</td>
                               <td>30</td>
                               <td>onClick={() => this.viewItem(item2Obj)}</td>
                         </tr>
                     </tbody>
                 </table> 
       }
       render(){
         return this.renderDisplay()
       }
}

我如何共享链接以便将我直接带到项目页面?

【问题讨论】:

    标签: javascript reactjs react-redux react-router state


    【解决方案1】:

    componentWillMount() 内部评估 this.props.location.pathname 中传递的内容。您应该能够从您的 URL 中获取 ID # 并更新您的状态。

    我看不出您是如何在现有代码中确定他们正在查看的项目。

    componentWillMount() {
       let id = '';
    
       console.log(this.props.location.pathname);
       // write a JS function to parse the ID from the URL here and save to 'id'
    
       // then if you have an ID, save whatever you need to state.    
       if(id !== '') {
          this.setState({
              canViewItem: true
          });
       }
    }
    

    附带说明一下,renderDisplayrenderMyList 应该包含在您的构造函数中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      相关资源
      最近更新 更多