setState()不会触发重新渲染

时间:2017-06-15 14:12:46

标签: javascript reactjs

这段代码有什么问题吗?

有问题的是:

// Update state and trigger re-render
// NOT WORKING
this.setState({ subsections });

调用setState()时未设置状态。虽然数据存在于subsections对象中。我在其他方法上使用了相同的代码模式,它按预期工作。

顺便说一下,如果我刷新页面,数据也会保存在Parse中。

import React from "react";
import Parse from 'parse';

import Subsections from './Subsections';
import AddSubsectionForm from './AddSubsectionForm';

class Manage extends React.Component {
  constructor() {
    super();

    this.addSubsection = this.addSubsection.bind(this);

    // Set initial state
    this.state = {
      subsections: {}
    };
  }

  addSubsection(subsection) {
    // Make copy of state
    const subsections = {...this.state.subsections};

    // Create new object
    var SubsectionTest = Parse.Object.extend('SubsectionTest');
    var subsectionTest = new SubsectionTest();

    // Save object, then update state on return
    subsectionTest.save({
      name: subsection.name,
      description: subsection.description
    }).then(function(newSubsection) {
      console.log('Has saved id of: '+newSubsection.id);

      // Add new subsection to local state
      subsections[newSubsection.id] = subsection;

      // Log updatd subsections object
      console.log(subsections);

      // Update state and trigger re-render
      // NOT WORKING
      this.setState({ subsections });
    },
    function(error) {
      console.log('Error:');
      console.log(error);
    });
  }

  /*
    Loads subsections from Parse and displays them.
    Code removed for clarity.
  */
  componentWillMount() {
    this.loadMenuItems();
  }

  render() {
    if (this.state.subsections) {
      return (
        <div className="subsections">
          <div className="mt3 border-top">
            <h3 className="mt1 bold s2">Subsections</h3>

            <div className="mt1">
              <Subsections subsections={this.state.subsections} />
            </div>
          </div>

          <div className="mt3 border-top">
            <AddSubsectionForm addSubsection={this.addSubsection}/>
          </div>
        </div>
      )
    }
  }
}

export default Manage;

2 个答案:

答案 0 :(得分:3)

您的问题是this并未受到您的承诺then处理程序的约束:

}).then(function(newSubsection) {

由于你正在使用es2015类,你可能可以使用箭头函数(将this绑定到它的词法范围):

}).then(newSubSection => {

另一种选择是明确绑定它:

}).then(function(newSubsection) {
...
}.bind(this));

答案 1 :(得分:1)

this的上下文丢失,您可以尝试将回调绑定到this

   var callback = function (newSubsection) {
       console.log('Has saved id of: ' + newSubsection.id);
           .....
       this.setState({
           subsections
       });
   };
   callback = callback.bind(this);
   subsectionTest.save({
       name: subsection.name,
       description: subsection.description
   }).then(callback),
   function (error) {
       console.log('Error:');
       console.log(error);
   });

如果您使用Babel preset stage 2,可以使用箭头功能

来实现此目的
      description: subsection.description
      }).then(newSubsection = > {
              console.log('Has saved id of: ' + newSubsection.id);