调用外部函数时如何重新渲染React组件?

时间:2019-06-28 14:37:24

标签: javascript reactjs publish-subscribe aws-amplify

我希望能够接收mqtt消息并将其显示在Web应用程序上。我正在使用AWS Amplify的PubSub,并且函数调用发生在类组件之外。我无法从其外部的函数直接访问任何实例函数/属性,但我需要某种方式来触发setState更改,以便可以重新呈现Web应用,对吧?

我已经尝试过直接从React类中直接调用该函数,但是仍然没有重新渲染发生。我试着制作一个外部变量,将收到的消息存储在其中,然后从React类访问该变量,但仍然没有触发器。然后,我进行了研究,发现我可以每隔几秒钟强制重新渲染一次,但读到应该避免这样做。我应该使用ComponentDidMount和setState函数,但不是真正了解如何使它工作。

我真正想做的就是获取消息并更新Web应用程序以显示新消息。听起来很简单,但我被困住了。

import...

var itemsArr = [];

function subscribe() {
    // SETUP STUFF
    Amplify.configure({
        ...
    });
    Amplify.addPluggable(new AWSIoTProvider({
        ...
    }));

    // ACTUAL SUBSCRIBE FUNCTION
    Amplify.PubSub.subscribe('item/list').subscribe({
        next: data => {
        // LOG DATA
        console.log('Message received', data);

        // GET NAMES OF ITEMS
        var lineItems = data.value.payload.lineItems;
        lineItems.forEach(item => itemsArr.push(item.name));
        console.log('Items Ordered', itemsArr);

        // THIS FUNCTION CALL TRIGGERS AN ERROR
        // CANT ACCESS THIS INSTANCE FUNCTION
        this.update(itemsArr);
    },
        error: error => console.error(error),
        close: () => console.log('Done'),
    });
}

// REACT COMPONENT
class App extends Component {
    constructor(props){
        super(props);

        this.state = {
            items:null,
        };
    }

    // THOUGHT I COULD USE THIS TO UPDATE STATE
    // TO TRIGGER A RE-RENDER
    update(stuff){
        this.setState({items: stuff});
    }

    render() {
        // THINK SUBSCRIBE METHOD CALL SHOULDN'T BE HERE
        // ON RE-RENDER, KEEPS SUBSCRIBING AND GETTING
        // SAME MESSAGE REPEATEDLY
        subscribe();
        console.log('items down here', itemsArr);

        return (
            <div className="App">
                <h1>Test</h1>
                <p>Check the console..</p>
                <p>{itemsArr}</p>
            </div>
        );
    }
}
export default App;

理想情况下,我希望在收到消息时显示项目列表的列,但是我目前遇到错误-“ TypeError:无法读取未定义的属性'update'”,因为类无法访问该类内部的更新功能。

1 个答案:

答案 0 :(得分:0)

在App组件内部放置subscription方法,以便您可以调用它。您可以在component首次呈现后,在componentDidMount生命周期中调用subscription方法以执行它(以获取项目)。然后,update方法将运行this.setState()(将您的项目存储在该状态中),导致App组件重新呈现。由于此重新渲染,您的this.state.items将包含某些内容,并将显示在您的段落中。

class App extends Component {
  constructor(props){
    super(props);

    this.state = {
        items: [],
    };

    this.subscribe = this.subscribe.bind(this); 
    this.update = this.update.bind(this);
  }

  update(stuff){
    this.setState({ items: stuff });
  }

  subscribe() {
    // SETUP STUFF
    Amplify.configure({
      ...
    });
    Amplify.addPluggable(new AWSIoTProvider({
      ...
    }));

    // ACTUAL SUBSCRIBE FUNCTION
    Amplify.PubSub.subscribe('item/list').subscribe({
      next: data => {
      // LOG DATA
      console.log('Message received', data);

      // GET NAMES OF ITEMS
      let itemsArr = [];
      var lineItems = data.value.payload.lineItems;
      lineItems.forEach(item => itemsArr.push(item.name));
      console.log('Items Ordered' + [...itemsArr]);
      this.update(itemsArr);
    },
      error: error => console.error(error),
      close: () => console.log('Done'),
    });
  }

  componentDidMount() {
    this.subscribe();
  }

  render() {

    console.log('items down here ' + [...this.state.items]);

    return (
        <div className="App">
            <h1>Test</h1>
            <p>Check the console..</p>
            <p>{this.state.items !== undefined ? [...this.state.items] : "Still empty"}</p>
        </div>
    );
  }
}

export default App;
相关问题