使用浏览器“后退”按钮时,React中的状态不一致并显示

时间:2017-11-29 13:57:42

标签: reactjs turbolinks

我在Rails 5.1应用程序中使用React 16.1.1(带有react-rails gem)。

特定页面上的React组件工作正常,除非使用浏览器“后退”按钮返回此页面(使用firefox / chrome / safari进行测试)。在这种情况下,显示与组件的状态不一致。我已经设置了问题演示https://lit-bastion-28654.herokuapp.com/

重现的步骤

  1. 在/ page1
  2. 点击“选择模式”按钮,将“selectionMode”设置为true
  3. 点击“第2页”
  4. 使用“后退”按钮返回第1页
  5. 预期行为:按钮为灰色(加载组件时,selectionMode重置为false)。观察到的行为:按钮仍然是蓝色的?!
  6. 在那里,您可以看到该按钮为蓝色,就好像selectionMode为真,但反应浏览器插件显示selectionMode为假。 React浏览器插件显示错误信息:它显示该按钮没有'btn-primary'类(如果selectionMode为false,这是正常的),但您可以在DOM中看到它具有'btn-primary '上课,因为它显得很蓝。

    这是我的代码:

    page1.html.erb

    <%= react_component("EditableCardList", { editable: true }) %>
    

    editable_card_list.js.jsx

    class EditableCardList extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          selectionMode: false
        };
    
        this.toggleSelectionMode = this.toggleSelectionMode.bind(this);
      }
    
    
      toggleSelectionMode() {
        this.setState(prevState => ({ selectionMode: !prevState.selectionMode }));
      }
    
    
      render() {
        if (this.props.editable === true)
          return (
            <div>
              <div className="row card-buttons">
                <div className="col-md-12">
                  <div className="pull-left">
                    <ManageCardsButtons
                      selectionMode={this.state.selectionMode}
                      toggleSelectionMode={this.toggleSelectionMode}
                    />
                  </div>
                </div>
              </div>
            </div>
          )
      }
    }
    

    manage_cards_buttons.js.jsx

    class ManageCardsButtons extends React.Component {
      constructor(props) {
        super(props);
      }
    
    
      render() {
        return (
          <span>
            <button type="button" className={`btn btn-default btn-sm ${this.props.selectionMode ? 'btn-primary' : ''}`}  onClick={this.props.toggleSelectionMode}>Selection mode</button>
    
            { this.props.selectionMode && <span>selection mode</span> }
          </span>
        )
      }
    }
    

    所以我的问题是:如何确保在浏览器中使用“后退”后,按钮被正确渲染(并显示为灰色而不是蓝色)?

    这个问题可能与turbolinks和缓存有关,但我还没有弄明白。

2 个答案:

答案 0 :(得分:1)

React和TurboLinks冲突,所以我的最终解决方案是禁用该特定页面上的TurboLinks缓存。

答案 1 :(得分:0)

当你返回到page1时,Component会重新渲染,并设置默认的selectionMode,在你的情况下是假的。

  1. 你可以使用redux。
  2. 您可以将selectionMode保存到您的 localStorage何时更改,默认情况下从中加载 存储