- 在第一次请求“show”页面时运行代码
- 阻止在其他页面(包括“index”页面)上运行代码
- 在随后的“show”页面请求中仅运行一次代码
以下是我使用的确切步骤和代码(我将尽可能简洁)。
I have a Rails 5.1 app with react installed with:
rails new myapp --webpack=react
I then create a simple Item scaffold to get some pages to play with:
rails generate scaffold Item name
I just add the following div element in the Show page (
app/views/items/show.html.erb
):<div id=hello></div>
Webpacker already generated a Hello component (
hello_react.jsx
) that I modified as following in ordered to use the above div element. I changed the original'DOMContentLoaded'
event:document.addEventListener('turbolinks:load', () => { console.log("DOM loaded.."); var element = document.getElementById("hello"); if(element) { ReactDOM.render(<Hello name="React" />, element) } })
I then added the following webpack script tag at the bottom of the previous view (
app/views/items/show.html.erb
):<%= javascript_pack_tag("hello_react") %>
I then run the
rails server
and thewebpack-dev-server
usingforeman start
(installed by addinggem 'foreman'
in theGemfile
) . Here is the content of theProcfile
I used:web: bin/rails server -b 0.0.0.0 -p 3000 webpack: bin/webpack-dev-server --port 8080 --hot
- 使用URL
http://localhost:3000/items
加载index页面。 - 单击New Item添加一个新项。Rails会将您重定向到项目的show页面,URL为
localhost:3000/items/1
。在这里,我们可以看到Hello React!消息。它工作得很好! - 使用URL
http://localhost:3000/items
重新加载index页面。该项按预期显示。 - 使用URL
http://localhost:3000/items/1
重新加载show页面。如预期显示Hello消息,同时有一条控制台消息。 - 使用URL
http://localhost:3000/items
重新加载index页面。 - 单击Show链接(应通过turbolink执行)。消息不显示,也没有控制台消息。
- 单击Back链接(应通过turbolink执行)回到index页面。
- 再次单击Show链接(应通过turbolink执行)。这次消息正常显示。而控制台消息则显示两次。
从那里开始,每次返回index并再次返回show页面都会在控制台显示两条消息。
注意:如果不使用(和替换)特定的div元素,而是让原始的hello_react
文件附加一个div元素,则此行为更加明显。
编辑:另外,如果我通过包括data: {turbolinks: false}
来更改link_to
链接。它也可以正常工作。就像我们使用浏览器地址栏中的URL加载页面一样。
我不知道自己做错了什么...
有什么想法吗?
编辑:如果有兴趣尝试,请将代码放入以下存储库: https://github.com/sanjibukai/react-turbolinks-test
rails new app --skip-turbolinks
,能完全解决这个问题吗? - Ibraheem Ahmed