【发布时间】:2021-08-05 14:59:33
【问题描述】:
我有一个使用 WebSocket 的 React Web 应用程序。我的主要 App 组件的一些子组件需要向 WebSocket 服务器发送消息,因此我将 WebSocket 对象从 App 传递给各自的子组件作为道具。由于 WebSocket 服务器的 URL 需要由用户在 HTML 表单中定义,因此 WebSocket 对象在应用程序的初始启动时是未定义的(这就是它稍后在使用setWebSocket 的输入处理程序的回调函数中定义的原因)。
当我将我的子组件 Map 定义为基于类的组件时,一切正常。但是,我想在整个应用程序中使用功能组件,并且当我将Map 定义为功能组件时,ws 属性将不可用(在下面的示例中:打印"no ws")。有趣的是,这只影响ws 属性。任何其他道具(这里作为示例:data)都能很好地传播。我在这里错过了什么?
编辑:
原来是由于nouislider-react。在我原来的帖子中,我简化了滑块组件部分,因为我无法想象是因为这个。我现在添加了 nouislider 代码。任何建议为什么这会阻止 ws 属性在功能组件的情况下仅被传递?
App.js
const App = () => {
const [webSocket, setWebSocket] = useState(undefined);
const [data, setData] = useState(null);
const getUserInput = (userInput) => {
setWebSocket(() => {
let url = "ws://" + userInput;
return new WSHandler(url);
});
}
return (
<Navbar parentCallback={getUserInput} />
<Map ws={webSocket} data={data} />
);
}
WSHandler.js
class WSHandler {
constructor(url) {
this.ws = new WebSocket(url);
this.binaryType = 'arraybuffer';
this.onopen = () => { ... }
this.onerror = () => { ... }
this.onmessage = () => { ... }
}
}
Map.js - 功能性
const Map = (props) => {
const onInputChange = () => {
if (props.ws) console.log("ws here");
else console.log("No ws"); //GOES HERE
if (props.data) console.log("data here"); //GOES HERE
else console.log("No data");
}
return (
<Nouislider
start={0}
range={{min: 0, max: 100}}
step={1}
onChange={onInputChange}
disabled={false}
/>
);
}
Map.js - 基于类
class Map extends Component {
onInputChange = () => {
if (this.props.ws) console.log("ws here"); // GOES HERE
else console.log("No ws");
if (this.props.data) console.log("data here"); //GOES HERE
else console.log("No data");
}
render() {
return (
<Nouislider
start={0}
range={{min: 0, max: 100}}
step={1}
onChange={onInputChange}
disabled={false}
/>
);
}
}
【问题讨论】:
-
看起来你只需要将 props 传递给 Map 组件中的 onInputChange 函数?
-
@danwebb 你的意思是像
const onInputChange = (props) => { ... }?不幸的是,这并没有奏效......此外,对于ws以外的道具,它实际上是有效的。
标签: reactjs websocket nouislider