【问题标题】:React-Router's Link-To updates the URL but doesn't refresh pageReact-Router 的 Link-To 更新 URL 但不刷新页面
【发布时间】:2015-11-12 18:22:16
【问题描述】:

我网站的标题有 10 个类别图像(链接)。每个都使用 React-Router 的 Link 来路由到每个类别各自的 categoryShow。

linkcategoryIndex 中有效,但在从 cagetoryShow 中单击时不再有效。单击它时它会正确更新浏览器,例如它会将pushState 推送到/cateories/18 和/categories/2,但浏览器不会刷新。

值得注意的是 链接 适用于所有其他索引类型和显示类型页面。它只是在 categoryShow 中不起作用。我想知道连续点击同名,例如 Link to="categoryShow",是否会以某种方式阻止路由器刷新页面?编辑:我尝试将其更改为 Link to= {"/categories/" + this.props.id } 并且它做同样的事情。

这是值得注意的组件结构。通过更新 URL,所有数据都已成功传递。只是在一种特殊情况下页面不会刷新:

-categoryShow
 -header (fetches and passes category data to child)
  -headerMenu (receives category data, passes on to child)
   -headerMenuCard (receives category data, uses the id in the link seen below)

headerMenuCard:

var HeaderMenuCard = React.createClass({

...
    return(
        <div >
            <Link to="categoryShow" params={{id: this.props.id}} ></Link>
        </div>
    )
})

这里是 CategoryShow,链接路由到的地方:

var CategoryShow = React.createClass({

getInitialState: function(){
    return{
        didFetchData: false,
        items: [],
        userID: localStorage.getItem('userID'),
        headerImage: "../categories.png"
    }
},

componentDidMount: function(){
    this.fetchData()
},

fetchData: function(){
    var data = {
       userID: this.state.userID
    }
    var params = this.props.params.id

    $.ajax({
        type: "GET",
        url: "/categories/" + params,
        data: data,
        dataType: 'json',
        success: function(data){
            this.setState({didFetchData: 'true', items: data.items})
        }.bind(this),
        error: function(data){
            alert("error! couldn't fetch category data")
        }
    })
},

render: function(){
    var itemArray = this.state.items.map(function(item){
        return <ItemCard name={item.name} key={item.id} id={item.id} photo_url={item.photo_url} description={item.description} userID={localStorage.getItem('userID')} like_status={item.like_status}  />
    })
    return(
        <div>
            <Header />

            <section className="body-wrapper">
                {itemArray}     
            </section>      
        </div>
    )
}
})

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您将在 props 中收到新参数,因此您只需运行 fetchDatacomponentWillReceivePropscomponentWillUpdate 中的任何其他逻辑。

    【讨论】:

    • 您应该使用 cmets 寻求发帖者的澄清,而不是答案。
    • 这让我明白我需要更新componentWillUpdate中的状态
    猜你喜欢
    • 2020-04-29
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2018-05-20
    • 2020-12-08
    相关资源
    最近更新 更多