尝试在 Reactjs 中实现一个简单的承诺 [英] Trying to implement a SIMPLE promise in Reactjs

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

问题描述

第一次在 React 中尝试 Promises.我有一个基本的承诺工作(从别人的代码中提取),但不知道如何调整它以使其有用.

到目前为止我所拥有的(在我的 render() 函数中)

 var promise = new Promise( (resolve, reject) => {让名字 = '戴夫'如果(姓名 === '戴夫'){resolve("Promise 成功解决");}别的 {拒绝(错误(承诺被拒绝"));}});promise.then(函数(结果){控制台日志(结果);//"Promise 成功解决"}, 错误 =>{控制台日志(错误);//错误:承诺被拒绝"});

果然,由于 promise 条件匹配(name === 'Dave'),我的控制台记录了 Promise 已成功解析.

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

 promise.then(function(result) {var newName = '鲍勃'}, 函数(错误){var newName = '匿名'});

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

{newName}

它说 newName 未定义.

我也试过:

 promise.then(function(result) {var newName = 结果}, 函数(错误){var newName = 错误});

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

我是不是想错了?当我的条件满足时,我怎样才能使它比仅仅记录一个字符串更有用?

任何帮助将不胜感激,因为这真的让我头疼...

<小时>

更新

 渲染(){var promise = new Promise((解决,拒绝)=> {让名字 = '保罗'如果(姓名 === '保罗'){resolve("Promise 成功解决");}别的 {拒绝(错误(承诺被拒绝"));}});让 obj = {newName: ''};promise.then( 结果 => {obj["newName"] = 结果}, 函数(错误){obj["newName"] = 错误});console.log(obj.newName)返回 (<div className="应用程序"><h1>你好世界</h1><h2>{obj.newName}</h2>

);}

解决方案

您正在以错误的方式使用 React.Promise 旨在稍后返回结果.当您的承诺被 resolvedrejected 时,您的 render 将完成执行,并且不会在承诺完成时更新.

render 方法应该只依赖于 props 和/或 state 来渲染所需的输出.对 propstate 的任何更改都会重新渲染您的组件.

  • 首先,确定您的 Promise 在组件的生命周期中应该去哪里(这里)
  • 在你的情况下,我会做以下事情

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

      初始化一个状态

      构造函数(道具){超级(道具);this.state = {名称: '',};}

    • 然后在适合您的 componentWillMountcomponentDidMount 上,调用那里的 promise

      componentWillMount() {var promise = new Promise((解决,拒绝)=> {让名字 = '保罗'如果(姓名 === '保罗'){resolve("Promise 成功解决");}别的 {拒绝(错误(承诺被拒绝"));}});让 obj = {newName: ''};promise.then( 结果 => {this.setState({name: result});}, 函数(错误){this.setState({name: error});});}

    • 然后在 render 方法中写一些类似的东西.

      render() {返回 (<div className="应用程序"><h1>你好世界</h1><h2>{this.state.name}</h2>

);}

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.

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"
  });

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

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'
  });

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

<h2>{newName}</h2>

It says newName is undefined.

I have also tried:

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

...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...


Update

 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>
    );
  }

解决方案

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 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.

  • First, identify where your Promise should go in the life cycle of the component(here)
  • In your case i would do the following

    • Initialize an state inside your constructor(ES6) or via getInitialState

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

    • 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});
       });
      }
      

    • 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 中实现一个简单的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆