首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么this.setState不更新this.states?

为什么this.setState不更新this.states?
EN

Stack Overflow用户
提问于 2017-01-21 16:07:30
回答 2查看 810关注 0票数 0

在我的代码中,this.setState似乎不是在更新this.states,而是触发了重新呈现。componentWillUpdate回调也显示了正确的参数。

代码语言:javascript
复制
class TimeButton extends React.Component {
  constructor(){
    super();
    this.states = {
      percentage : 50
    }
  }
  componentWillUpdate(nextProps, nextState){
    console.log("componentWillUpdate currentstate")
    console.log(this.states);
    console.log("componentWillUpdate nextstate")
    console.log(nextState);

  }

  componentDidMount(){
    let component = this;
    console.log("componentDidMount");
    console.log(this.states);

    this.setState({
      percentage : 70,
      test : 10101010
    }, () => {
      console.log("callback setState");
      console.log(this.states);
    })

  }

  componentWillUnmount(){
  }

  handleClick(){
    this.props.onClick(component.props);
  }

  render(){
    console.log("render");
    console.log(this.states);
    let component = this;
    let { buttonInnerRadius, buttonOuterRadius, x, y } = this.props
    return (
      <Group onClick={component.handleClick.bind(component)}>
        <CircularBar x={x} y={y} innerRadius={buttonInnerRadius} outerRadius={buttonOuterRadius} ref="bar" percentage={this.states.percentage}></CircularBar>
        <Circle x={x} y={y} radius={buttonOuterRadius}></Circle>
      </Group>
    )
  }
}

所以这是结果

我在这里做错什么了吗?setState以前在我编码的其他地方工作过

如果我做了愚蠢的事

代码语言:javascript
复制
this.states.percentage = 70
this.states.test = 101010
this.forceUpdate()

它工作得很好,但这看起来是个坏主意。

到目前为止我已经退房了

为什么我的setState不能工作?[复本]

为什么“this.setState”不起作用?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-21 16:15:21

这只是你代码中的一个错误。组件的状态称为state,而不是states

票数 2
EN

Stack Overflow用户

发布于 2017-01-21 17:48:39

@Tholle是精确的,this.state存在于React类模块中。没有比this.states更好的了。

代码语言:javascript
复制
/**
 * Module for creating composite components.
 *
 * @class ReactClass
 */
var ReactClass = {

  createClass: function(spec) {
    // To keep our warnings more understandable, we'll use a little hack here to
    // ensure that Constructor.name !== 'Constructor'. This makes sure we don't
    // unnecessarily identify a class without displayName as 'Constructor'.
    var Constructor = identity(function(props, context, updater) {
      // This constructor gets overridden by mocks. The argument is used
      // by mocks to assert on what gets mounted.

      if (__DEV__) {
        warning(
          this instanceof Constructor,
          'Something is calling a React component directly. Use a factory or ' +
          'JSX instead. See: https://facebook.github.io/react/warnings/legacy-factories.html'
        );
      }

      // Wire up auto-binding
      if (this.__reactAutoBindPairs.length) {
        bindAutoBindMethods(this);
      }

      this.props = props;
      this.context = context;
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;

      this.state = null;

您可以通过setState方法将所需的任何东西放入this.state中。这里,我用值a设置状态'a'

代码语言:javascript
复制
 this.setState({ a: 'a' });

如果我做了愚蠢的事 this.states.percentage = 70 this.states.test = 101010 this.forceUpdate()

这将是动态添加states属性。然而,这是不明智的。

状态应该始终使用setState方法来设置,即使您改进了错误,也不应该直接设置。这应该像这里解释的那样异步地完成。

代码语言:javascript
复制
File: react/docs/js/react.js
1220: /**
1221:  * Sets a subset of the state. Always use this to mutate
1222:  * state. You should treat `this.state` as immutable.
1223:  *
1224:  * There is no guarantee that `this.state` will be immediately updated, so
1225:  * accessing `this.state` after calling this method may return the old value.
1226:  *
1227:  * There is no guarantee that calls to `setState` will run synchronously,
1228:  * as they may eventually be batched together.  You can provide an optional
1229:  * callback that will be executed when the call to setState is actually
1230:  * completed.
1231:  *
1232:  * When a function is provided to setState, it will be called at some point in
1233:  * the future (not synchronously). It will be called with the up to date
1234:  * component arguments (state, props, context). These values can be different
1235:  * from this.* because your function may be called after receiveProps but before
1236:  * shouldComponentUpdate, and this new state, props, and context will not yet be
1237:  * assigned to this.
1238:  *
1239:  * @param {object|function} partialState Next partial state or function to
1240:  *        produce next partial state to be merged with current state.
1241:  * @param {?function} callback Called after state is updated.
1242:  * @final
1243:  * @protected
1244:  */
1245: ReactComponent.prototype.setState = function (partialState, callback) {
1246:   !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "development" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0;
1247:   this.updater.enqueueSetState(this, partialState);
1248:   if (callback) {
1249:     this.updater.enqueueCallback(this, callback, 'setState');
1250:   }
1251: };

正如所解释的,这里:唯一可以分配this.state的地方是构造函数。

直接设置状态不会重新呈现组件,这应该是setState()方法背后的想法。

还可以将多个setState()调用批处理到单个更新中以提高性能。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41781483

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档