2016-02-12 42 views
6

如果我有一个简单的反应组件,它记录按钮的点击次数,并且每次点击都记录一个新的历史记录状态而不更改url。当用户点击返回时,我该如何恢复状态?如何使用反应恢复返回按钮的状态

我可以像使用本地JavaScript历史记录对象一样在这里执行操作,但当用户转换回第一个状态并从不同组件返回到此状态的最后一个状态时,它会失败。

我怀疑有更好的办法使用react-router(1.0)来做到这一点吗?

import React, { Component } from 'react'; 

export default class Foo extends Component { 
    state = { 
    clickCount: 0, 
    }; 

    componentWillMount() { 
    window.onpopstate = (event) => { 
     if (event.state.clickCount) { 
     this.setState({ clickCount: event.state.clickCount }); 
     } 
    }; 
    } 

    onClick() { 
    const newClickCount = this.state.clickCount + 1; 
    const newState = { clickCount: newClickCount }; 
    this.setState(newState); 
    history.pushState(newState, ''); 
    } 

    render() { 

    return (
     <div> 
     <button onClick={this.onClick.bind(this)}>Click me</button> 
     <div>Clicked {this.state.clickCount} times</div> 
     </div> 
    ); 
    } 
} 
+0

在react-router中签出浏览器历史记录。 –

+0

也许[这个答案](http://stackoverflow.com/questions/29442206/how-to-pass-both-this-state-and-this-props-to-routes-using-react-router)帮助。 –

+0

您可以将localStorage用于您的状态。为什么不? –

回答

1

的localStorage甚至饼干的选择,但可能不是最好的办法。您应该将计数存储在数据库中,这样您可以将构造函数中的初始状态设置为保存在数据库中的最后一个值。

另一种选择是,如果您只需要在客户端(而不是在数据库中)持续计数,则使用闭包。

// CountStore.js 
var CountStore = (function() { 
    var count = 0; 

    var incrementCount = function() { 
    count += 1; 
    return count; 
    }; 

    var getCount = function() { 
    return count; 
    }; 

    return { 
    incrementCount: incrementCount, 
    getCount: getCount 
    } 

})(); 

export default CountStore; 

所以你的代码会变成下面的代码。

import React, { Component } from 'react'; 
import CountStore from './CountStore'; 

export default class Foo extends Component { 
    state = { 
    clickCount: CountStore.getCount() 
    }; 

    componentWillMount() { 
    window.onpopstate = (event) => { 
     if (event.state.clickCount) { 
     this.setState({ clickCount: event.state.clickCount }); 
     } 
    }; 
    } 

    onClick() { 
    const newClickCount = CountStore.incrementCount(); 
    const newState = { clickCount: newClickCount }; 
    this.setState(newState); 
    } 

    render() { 

    return (
     <div> 
     <button onClick={this.onClick.bind(this)}>Click me</button> 
     <div>Clicked {this.state.clickCount} times</div> 
     </div> 
    ); 
    } 
} 

使用react-router可能有更简洁的方法,但这是一种选择。

相关问题