【问题标题】:Insert Laravel Echo in React [duplicate]在 React 中插入 Laravel Echo [重复]
【发布时间】:2021-06-06 12:12:00
【问题描述】:

我有以下脚本在welcome.blade.php 中完美运行:

<script>
            Echo.channel('home')
                .listen('NewPatient',(e) => {console.log(e.patient);
                  })            
</script>

Home 是频道名称,NewPatient 是事件名称。

如何在 React 组件中实现此脚本,以便我可以在该组件中精确显示数据?

患者组件在反应:

import React,{Component} from 'react';
import axios from 'axios';
import Echo from "laravel-echo";
 
class Patient extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            patients : []
        };
    }

      
        componentDidMount() {
            axios.get('api/patients')
            .then(response => {this.setState({patients: response.data})})
            .catch(err => console.log(err));   
        }

        
      
        render() {
          return (
            <ul>
              { this.state.patients.map(patient => <li>{patient.nom}</li>)}
            </ul>
          )
        }
      }

export default Patient;

当我尝试将脚本粘贴到 ComponentDidMount 区域时,出现laravel_echo__WEBPACK_IMPORTED_MODULE_2__.default.channelCan't perform a React state update on an unmounted component 等错误

【问题讨论】:

  • 你也没有在任何地方包含 Laravel Echo 代码。您在文件中包含了Echo,但没有在任何地方使用该组件。
  • bootstrap.js初始化

标签: javascript reactjs laravel laravel-echo


【解决方案1】:

解决了!在我的 ComponentDidmount 代码中的 Echo 旁边添加了window.

window.Echo.channel('home')
                .listen('NewPatient',(e) => {console.log(e.patient);
                  })    

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2016-01-05
    • 2019-06-17
    • 2020-09-19
    • 2022-12-05
    • 1970-01-01
    • 2020-02-28
    • 1970-01-01
    • 2020-01-28
    相关资源
    最近更新 更多