【问题标题】:How to load data from a different component after submititng form from another component in ReactJs从 ReactJs 中的另一个组件提交表单后如何从另一个组件加载数据
【发布时间】:2020-08-21 18:58:12
【问题描述】:

我有一个事件模型。在我的活动中,人们可以通过单击按钮来表明他们是否正在参加活动,当他们通过单击按钮表明他们正在参加活动时,会弹出一个模态对话框询问他们是否也想带朋友一起参加对于活动,如果他们说是,它会要求他们选择他们想带多少人,他们将从数字下拉列表中选择并提交。在提交所有内容后,它会加上来的人以及这个人来的人数,然后一起显示。

注意:模态对话框来自我在 Event 组件中需要的另一个组件。

我现在面临的问题是,除非我刷新页面,否则我的视图只会更新即将到来的人,但不会更新该人带来的人数。这在我使用基于类的组件时有效,但在将代码更改为基于函数的组件后它停止工作。

如何让浏览器在不刷新页面的情况下自动更新?

这是我的沙盒链接https://codesandbox.io/s/compassionate-sanne-pmmx6?file=/event-comments.component.js

请在沙箱中使用此 URL https://pmmx6.csb.app/events/ 只需在其他沙箱提供的 URL 后添加events 即可加载事件数据,因为沙箱内未显示事件链接(我不知道为什么)

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    也许你可以通过使用事件发射器来解决这个问题

    使用

    EventEmitter.subscribe('refresh', (event)=>this.refresh(event)) 
    

    创建事件

    当你想执行它时,你使用

    EventEmitter.dispatch('refresh', event)
    

    一步一步创建一个eventEmitter:

    • 创建 eventEmitter.js 文件:
    const EventEmitter = {
      events: {},
      dispatch: function (event, data) {
        if (!this.events[event]) return;
        this.events[event].forEach(callback => callback(data))
        console.log("Dispatched: " + event)
      },
      subscribe: function (event, callback) {
        if (!this.events[event]) this.events[event] = [];
        this.events[event].push(callback)
        console.log("Subscribed: " + event)
      },
      unsubscribe: function(event) {
        if (this.events[event]) {
          delete this.events[event]
        }
        console.log("Unsubscribed: " + event)
      }
    };
    
    module.exports = {EventEmitter};
    
    • 在要首先刷新的组件中,导入 eventEmitter.js。例如:
    import {EventEmitter} from "./tools/eventEmitter";
    
    • 然后你使用 subscribe() 创建一个事件:
    EventEmitter.subscribe('refresh', (event)=>this.refresh(event)) 
    

    refresh 是指派发事件时将执行的函数

    • 最后,当你想刷新组件时,使用.dispatch():
    EventEmitter.dispatch('refresh', event)
    

    这将执行 this.refresh() 第一个组件函数

    如果你想看看https://medium.com/@lolahef/react-event-emitter-9a3bb0c719是一个很好的事件发射器的页面

    【讨论】:

    • 谢谢,但是我没能在我的代码中实现它,我猜我的 react 知识还不够好,不知道怎么做,我用 react 还不到两个月。如果您能给我更多指导,我将不胜感激@Ivan
    • 是的,当然,随便问,我现在就更新我的答案,因为太长了
    【解决方案2】:

    谢谢大家,我通过在 API 调用后添加 events 解决了这个问题。我在 React Facebook 页面上看到了这个例子。此方法会在发生更改时重新加载数据。

    const [events, setEventData] = useState([]);
    
    useEffect(() => {
    axios
      .get(
        "https://cryptic-shelf-72177.herokuapp.com/events/" +
          props.match.params.id +
          "/eventcomments"
      )
    
      .then((response) => {
        setEventData(response.data);
      })
    
      .catch(function (error) {
        console.log(error);
      });
    }, [events]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 2023-04-08
      • 2015-05-08
      • 1970-01-01
      • 2022-12-22
      • 1970-01-01
      • 2019-12-02
      相关资源
      最近更新 更多