我在Rails 5.1应用程序中使用React 16.1.1(带有react-rails gem)。
特定页面上的React组件工作正常,除非使用浏览器“后退”按钮返回此页面(使用firefox / chrome / safari进行测试)。在这种情况下,显示与组件的状态不一致。我已经设置了问题演示:https://lit-bastion-28654.herokuapp.com/。
重现的步骤:
在那里,您可以看到该按钮为蓝色,就好像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和缓存有关,但我还没有弄明白。
答案 0 :(得分:1)
React和TurboLinks冲突,所以我的最终解决方案是禁用该特定页面上的TurboLinks缓存。
答案 1 :(得分:0)
当你返回到page1时,Component会重新渲染,并设置默认的selectionMode,在你的情况下是假的。