如何正确地重写AngularJS代码到React?

huangapple go评论58阅读模式
英文:

How to properly re-write AngularJS code to React?

问题

以下是您提供的代码的中文翻译部分:

AngularJS(部分代码):

<script>
    var app = angular.module('myapp', []);
    
    app.controller('MainCtrl', function($scope) {
    
     // 在初始化时调用,如果本地存储中存在数组则读取
      $scope.checkAndInitiateFromLocalStorage = function() {
        var readArrayStr = localStorage.getItem('messagingArray');
        if (readArrayStr && readArrayStr.length > 0) {
          $scope.arr = JSON.parse(readArrayStr);
        } else {
          $scope.arr = [{
              name: "user1"
            },
            {
              name: "user2"
            },
            {
              name: "user3"
            },
            {
              name: "user4"
            }
          ];
        }
      }

      // 在每次更新时调用,将最新状态存储在本地存储中
      $scope.updateLocalStorage = function() {
        localStorage.setItem('messagingArray', JSON.stringify($scope.arr));
        /* console.log("更新本地存储!!"); */
      }

      $scope.checkAndInitiateFromLocalStorage();
    });
</script>

React(部分代码):

<script src="react.min.js"></script>
<script src="react-dom.min.js"></script>
<script src="browser.min.js"></script>

<div id="app"></div>

<script type="text/babel">

class Application extends React.Component {
  constructor(props) {
    super(props);

    // 在初始化时调用,如果本地存储中存在数组则读取
    const checkAndInitiateFromLocalStorage = () => {
      var readArrayStr = localStorage.getItem('messagingArray');
      if (readArrayStr && readArrayStr.length > 0) {
        this.state.arr = JSON.parse(readArrayStr);
      } else {
        this.state = {
          arr: [
            { name: "user1" },
            { name: "user2" },
            { name: "user3" },
            { name: "user4" }
          ]
        };
      }
    }

    this.checkAndInitiateFromLocalStorage = this.checkAndInitiateFromLocalStorage.bind(this);
    this.updateLocalStorage = this.updateLocalStorage.bind(this);
  }

  // 在每次更新时调用,将最新状态存储在本地存储中
  updateLocalStorage() {
    localStorage.setItem('messagingArray', JSON.stringify(this.state.arr));
  };

  componentDidMount() {
    this.checkAndInitiateFromLocalStorage(); 
    this.updateLocalStorage();
  }

  render() {
    return (
      <div>
        <h3>显示数据</h3>
        <ul>
          {this.state.arr.map((obj, i) => (
            <li key={i}>
              {obj.name} - {obj.name}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<Application />, document.getElementById('app'));

</script>

这是您提供的AngularJS和React代码的翻译。如有其他问题或需要进一步的翻译,请告诉我。

英文:

I have the code below which reads stores and updates data to and from from localstorage and it works fine with AngularJS.

Here is my issue:
Am trying to re-write the Angularjs code to React but it throws error unexpected token.

AngularJS:

&lt;script&gt;
var app = angular.module(&#39;myapp&#39;, []);
app.controller(&#39;MainCtrl&#39;, function($scope) {
//called at initiazation, reads from localstorage if array is present there
$scope.checkAndInitiateFromLocalStorage = function() {
var readArrayStr = localStorage.getItem(&#39;messagingArray&#39;);
if (readArrayStr &amp;&amp; readArrayStr.length &gt; 0) {
$scope.arr = JSON.parse(readArrayStr);
} else {
$scope.arr = [{
name: &quot;user1&quot;
},
{
name: &quot;user2&quot;
},
{
name: &quot;user3&quot;
},
{
name: &quot;user4&quot;
}
];
}
}
//called at each update, stores the latest status in localstorage
$scope.updateLocalStorage = function() {
localStorage.setItem(&#39;messagingArray&#39;, JSON.stringify($scope.arr));
/* console.log(&quot;updated local storage !!&quot;); */
}
$scope.checkAndInitiateFromLocalStorage();
});
&lt;/script&gt;

React:

    &lt;script src=&quot;react.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;react-dom.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;browser.min.js&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;app&quot;&gt;&lt;/div&gt;
&lt;script type=&quot;text/babel&quot;&gt;
class Application extends React.Component {
constructor(props) {
super(props);
//called at initiazation, reads from localstorage if array is present there
//const checkAndInitiateFromLocalStorage () {
const checkAndInitiateFromLocalStorage = () =&gt; {
var readArrayStr = localStorage.getItem(&#39;messagingArray&#39;);
if (readArrayStr &amp;&amp; readArrayStr.length &gt; 0) {
this.state.arr = JSON.parse(readArrayStr);
} else {
this.state = {
arr: [
{      name: &quot;user1&quot;},
{      name: &quot;user2&quot;},
{      name: &quot;user3&quot;},
{      name: &quot;user4&quot;}
],
};
}
}
this.checkAndInitiateFromLocalStorage = this.checkAndInitiateFromLocalStorage.bind(this);
this.updateLocalStorage = this.updateLocalStorage.bind(this);
}
//called at each update, stores the latest status in localstorage
updateLocalStorage() {
localStorage.setItem(&#39;messagingArray&#39;, JSON.stringify(this.state.arr));
};
componentDidMount() {
this.checkAndInitiateFromLocalStorage(); 
this.updateLocalStorage();
}
render() {
return (
&lt;div&gt;
&lt;h3&gt;Display Data&lt;/h3&gt;
&lt;ul&gt;
{this.state.arr.map((obj, i) =&gt; (
&lt;li key={i}&gt;
{obj.name} - {obj.name}
&lt;/li&gt;
))}
&lt;/ul&gt;
&lt;/div&gt;
);
}
}
ReactDOM.render(&lt;Application /&gt;, document.getElementById(&#39;app&#39;));
&lt;/script&gt;

Here is the updated react error message:

Uncaught TypeError: Cannot read properties of undefined (reading &#39;bind&#39;)
at new Application (eval at transform.run  

答案1

得分: 0

这个问题通过将checkAndInitiateFromLocalStorage的定义移到构造函数之外来解决。

以下是代码

class Application extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      arr: [
        { name: "user1" },
        { name: "user2" },
        { name: "user3" },
        { name: "user4" }
      ]
    };

    this.checkAndInitiateFromLocalStorage = this.checkAndInitiateFromLocalStorage.bind(this);
    this.updateLocalStorage = this.updateLocalStorage.bind(this);
  }

  checkAndInitiateFromLocalStorage() {
    var readArrayStr = localStorage.getItem('messagingArray');
    if (readArrayStr && readArrayStr.length > 0) {
      this.state.arr = JSON.parse(readArrayStr);
    } else {
      this.state.arr;
    }
  }

  updateLocalStorage() {
    localStorage.setItem('messagingArray', JSON.stringify(this.state.arr));
  }

  componentDidMount() {
    this.checkAndInitiateFromLocalStorage();
    this.updateLocalStorage();
  }

  render() {
    return (
      <div>
        <h3>Display Data</h3>
        <ul>
          {this.state.arr.map((obj, i) => (
            <li key={i}>
              {obj.name} - {obj.name}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

ReactDOM.render(<Application />, document.getElementById('app'));

请注意,我已经将HTML标记的编码(如&quot;&lt;)还原为原始代码,以便更容易阅读。

英文:

This issue was solved by Moving the definition of checkAndInitiateFromLocalStorage outside of the constructor.

Here is the code below

class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
arr: [
{      name: &quot;user1&quot;},
{      name: &quot;user2&quot;},
{      name: &quot;user3&quot;},
{      name: &quot;user4&quot;}
],
};
this.checkAndInitiateFromLocalStorage = this.checkAndInitiateFromLocalStorage.bind(this);
this.updateLocalStorage = this.updateLocalStorage.bind(this);
}
checkAndInitiateFromLocalStorage () {
//const checkAndInitiateFromLocalStorage = () =&gt; {
var readArrayStr = localStorage.getItem(&#39;messagingArray&#39;);
if (readArrayStr &amp;&amp; readArrayStr.length &gt; 0) {
this.state.arr = JSON.parse(readArrayStr);
} else {
this.state.arr;
}
}
//called at each update, stores the latest status in localstorage
updateLocalStorage() {
localStorage.setItem(&#39;messagingArray&#39;, JSON.stringify(this.state.arr));
};
componentDidMount() {
this.checkAndInitiateFromLocalStorage(); 
this.updateLocalStorage();
}
render() {
return (
&lt;div&gt;
&lt;h3&gt;Display Data&lt;/h3&gt;
&lt;ul&gt;
{this.state.arr.map((obj, i) =&gt; (
&lt;li key={i}&gt;
{obj.name} - {obj.name}
&lt;/li&gt;
))}
&lt;/ul&gt;
&lt;/div&gt;
);
}
}
ReactDOM.render(&lt;Application /&gt;, document.getElementById(&#39;app&#39;));

huangapple
  • 本文由 发表于 2023年2月14日 06:10:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441681.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定