gpt4 book ai didi

javascript - 将参数传递给另一个组件时出错

转载 作者:行者123 更新时间:2023-12-01 02:20:07 26 4
gpt4 key购买 nike

这个问题真的让我很困惑,当连接打开并且我控制台日志 session 工作正常时,我得到了数据,但是当我尝试将 session 传递到调用函数之外并在组件渲染中控制台 sessionVar 时,我未获取数据

import React, {Component} from 'react';
import autobahn from 'autobahn';

let sessionVar = undefined
class App extends Component {

componentWillMount() {
this.Call();
}
Call = () => {
var connection = new autobahn.Connection({ url: 'ws://127.0.0.1:9000/', realm: 'realm1' });

connection.onopen = function (session) {
console.log(session, 'This show data when component mount')
sessionVar = session
};

connection.open();
}
render() {
console.log(sessionVar, 'Im getting undefined')
return (
<div>
<Two session={sessionVar} />
</div>
)
}
}

export default App;

最佳答案

改用state。请参阅docs about React state

const Two = (props) => <h1>{props.session}</h1>

class App extends React.Component {
constructor(props) {
super(props)
this.state = {
sessionVar: undefined
}
}

componentWillMount() {
this.call()
}

call = () => {
// Do you fetch session related stuff as normal
let session = 'session fetched'
// simulate a delay due to connection
setTimeout(() => {
this.setState({
sessionVar: session
}); // setState triggers rerendering
}, 1000);
}
render() {
return (
<div>
<Two session={this.state.sessionVar} />
</div>
)
}
}

ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

关于javascript - 将参数传递给另一个组件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49263030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com