我有一个rails + react应用程序(单独的项目),我做了一个ActionCable websocket从后端发送简单的消息到前端。websocket工作,我可以看到前端的一切,但我不能实时看到更新,只有刷新后。我不知道如何实现实时更新。
下面是我的代码:import PropTypes from 'prop-types'
import { Switch, Route } from 'react-router-dom'
import actionCable from 'actioncable'
import { DUMMY_QUERY } from 'Queries'
// app/javascript/packs/messages.js
import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom'
import MessagesChannel from './channels/messages_channel'
function useForceUpdate(){
const [value, setValue] = useState(0); // integer state
return () => setValue(value => value + 1); // update the state to force render
}
function Dummy() {
const [messages, setMessages] = useState([])
const [message, setMessage] = useState('')
const [rerender, setRerender] = useState(false);
useEffect(() => {
MessagesChannel.received = (data) => {
setMessages(data.messages)
console.log(data)
}
}, [])
/*const handleSubmit = async (e) => {
e.preventDefault()
// Add the X-CSRF-TOKEN token so rails accepts the request
await fetch('http://localhost:3000/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message }),
})
setMessage('')
}*/
return (
<div>
<ul>
{messages.map((message) => (
<li key={message.id}>{message.content}</li>
))}
</ul>
</div>
)
}
export default Dummy
有源电缆也属于前端组件。我从来没有使用它与react一起,但与纯js它看起来像这样:
导入库(consumer.js):
import { createConsumer } from "@rails/actioncable"
export default createConsumer()
加载repo (index.js)中定义的所有通道:
const channels = require.context('.', true, /_channel.js$/)
channels.keys().forEach(channels)
为每个通道定义一个js文件(message_channel.js):
import consumer from "./consumer"
consumer.subscriptions.create("MessagesChannel", {
connected() {
// Called when the subscription is ready for use on the server
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
// Called when there's incoming data on the websocket for this channel
console.log(data)
}
});
编辑:刚刚发现还有一个前端组件的npm包。