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

时间:2018-03-13 18:08:36

标签: javascript reactjs autobahn

这个问题让我很困惑,当连接打开并且我控制台日志会话它工作正常我得到了数据但是当我尝试将会话传递到调用函数的一侧并控制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;

1 个答案:

答案 0 :(得分:2)

请改用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>