【问题标题】:Meteor method call with useTracker and render html使用 useTracker 调用 Meteor 方法并渲染 html
【发布时间】:2021-08-20 20:56:46
【问题描述】:

这里是流星新手,我想对流星方法进行流星调用,该方法向第 3 方 API 发出获取请求,并将返回的 JSON 响应转发到我的初始流星调用。

我想使用返回的 JSON 响应来呈现我的 html 代码

这是我的带有流星方法的 js 文件

Meteor.methods({
  'jira.get'(projectName, maxResult) {
    if (!this.userId) {
      throw new Meteor.Error('Not authorized.');
    }
    check(projectName, String);
    check(maxResult, String);
    const base64Auth = Meteor.users.findOne({ _id: this.userId }).Authorization;

    const options = {
      method: 'GET',
      url: `https://myCompany.com/.../search?jql=project=${projectName}&maxResults=${maxResult}`,
      headers: {
        Authorization: base64Auth,
      },
    };

    const future = new Future();

    request(options, function(error, response) {
      if (error) throw new Error(error);
      const jiraResponse = JSON.parse(response.body);
      future.return(jiraResponse);
    });

    return future.wait();
  },
});

我调用上述 Meteor 方法的 JSX 文件如下

export const App = () => {
   
    Meteor.call('jira.get', project='test', maxResult = '10', (error, jiraResponse) => {
      console.log("this is working fine: "jiraResponse)
    });

    console.log('this is undefined', jiraResponse)
}

如果我使用下面的 useState,最初最后一个控制台日志console.log(jiraResp) 按预期打印{},但之后它会进入无限循环并使用正确的数据

 const [ jiraResp, setjiraResp ] = useState({})
  Meteor.call('jira.get', project='test', maxResult = '10', (error, jiraResponse) => {
    if (jiraResponse){
      console.log("got the resp ")
      setjiraResp(jiraResponse);
    }
    else{
      console.log("not recieved")
    }
  });
  console.log(jiraResp)

我如何获得流星呼叫的响应并只更新一次我的 jiraResponse?

【问题讨论】:

    标签: javascript reactjs meteor use-state


    【解决方案1】:

    在方法回调中设置jiraResp 将触发重新渲染,并且由于您是在渲染方法本身中进行方法调用,它会重复调用,从而循环。

    你需要使用useEffect:

    const [ jiraResp, setjiraResp ] = useState({});
    useEffect(() =>
      Meteor.call('jira.get', project = 'test', maxResult = '10', (error, jiraResponse) => {
        if (jiraResponse) {
          console.log("got the resp ");
          setjiraResp(jiraResponse);
        } else {
          console.log("not recieved");
        }
      }), []);
    console.log(jiraResp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 2013-10-02
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2014-10-18
      相关资源
      最近更新 更多