尝试在Reactjs中实现SIMPLE Promise [英] Trying to implement a SIMPLE promise in Reactjs

查看:59
本文介绍了尝试在Reactjs中实现SIMPLE Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需在React中第一次尝试Promises.我有一个基本的诺言(从别人的代码中剥夺了),但是不知道如何使它变得有用.

Just trying out Promises for the first time in React. I have a basic promise working (ripped from someone else's code), but don't know how to adapt it to be useful.

到目前为止(在我的render()函数中)有什么

What I have so far (within my render() function)

  var promise = new Promise( (resolve, reject) => {

     let name = 'Dave'

     if (name === 'Dave') {
        resolve("Promise resolved successfully");
     }
     else {
        reject(Error("Promise rejected"));
     }
  });

  promise.then(function(result) {
     console.log(result); // "Promise resolved successfully"
  }, err => {
     console.log(err); // Error: "Promise rejected"
  });

果然,由于promise条件已匹配(name === 'Dave'),因此我的控制台记录了Promise resolved successfully.

Sure enough, as the promise conditional is matched (name === 'Dave'), my console logs Promise resolved successfully.

但是,我不知道在使用Promise时如何为变量赋值.例如:

However, I don't know how to assign a value to a variable when using the promise. For example:

  promise.then(function(result) {
     var newName = 'Bob'
  }, function(err) {
     var newName = 'Anonymous'
  });

然后当我尝试在render()的return语句中返回此值时,如下所示:

And then when I try to return this value in render()'s return statement, like so:

<h2>{newName}</h2>

它说newName是未定义的.

It says newName is undefined.

我也尝试过:

  promise.then(function(result) {
     var newName = result
  }, function(err) {
     var newName = error
  });

...预计此操作会将resolveerror字符串分配给newName变量,但不会.

...expecting this would assign the resolve or error string into newName variable, but nope.

我在想这个错误的方式吗?除了满足条件时才记录字符串,我如何使它更有用?

Am I thinking about this the wrong way? How can I make this more useful than just logging a string when my conditional is met?

任何帮助将不胜感激,因为这确实使我的头部受伤...

Any help would be appreciated, because this is really making my head hurt...

 render() {

      var promise = new Promise( (resolve, reject) => {

         let name = 'Paul'

         if (name === 'Paul') {
            resolve("Promise resolved successfully");
         }
         else {
            reject(Error("Promise rejected"));
         }
      });

      let obj = {newName: ''};

      promise.then( result => {
         obj["newName"] = result
      }, function(error) {
         obj["newName"] = error
      });

      console.log(obj.newName)

    return (
      <div className="App">
         <h1>Hello World</h1>
         <h2>{obj.newName}</h2>
      </div>
    );
  }

推荐答案

您以错误的方式使用了React. Promise用于在以后的某个时间点返回结果.到您的诺言成为resolvedrejected时,您的render就已经完成执行,并且诺言完成时不会更新.

You are using React in a wrong way. A Promise is designed to return result at a later point of time. By the time your promise has been resolved or rejected, your render would have finished execution and it wont update when the promise completes.

render方法应仅依赖于props和/或state来呈现所需的输出.对propstate所做的任何更改都会re-render您的组件.

render method should only depend on props and/or state to render the desired output. Any change to prop or state would re-render your component.

  • 首先,确定您的Promise在组件的生命周期中的位置(
  • First, identify where your Promise should go in the life cycle of the component(here)
  • In your case i would do the following

  • 在构造函数(ES6)内或通过getInitialState

constructor(props) {
  super(props);
  this.state = {
    name: '',
  };
}

  • 然后在适合您的componentWillMountcomponentDidMount上,在那称呼诺言

  • Then on componentWillMount or componentDidMount which ever suits you, call the promise there

    componentWillMount() {
     var promise = new Promise( (resolve, reject) => {
    
      let name = 'Paul'
    
      if (name === 'Paul') {
       resolve("Promise resolved successfully");
      }
      else {
       reject(Error("Promise rejected"));
      }
     });
    
     let obj = {newName: ''};
    
     promise.then( result => {
      this.setState({name: result});
     }, function(error) {
      this.setState({name: error});
     });
    }
    

  • 然后在render方法中编写与此类似的内容.

  • Then in render method write something similar to this.

    render() {
     return (
      <div className="App">
       <h1>Hello World</h1>
       <h2>{this.state.name}</h2>
      </div>
     );
    }
    

  • 这篇关于尝试在Reactjs中实现SIMPLE Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆