【问题标题】:Setting mobX state from inside a React-Apollo component从 React-Apollo 组件内部设置 mobX 状态
【发布时间】:2018-09-19 11:22:41
【问题描述】:

尝试设置输入元素的 onChange 状态时,我无法更改状态。 React-Apollo 组件需要一个返回一些 JSX 的子函数。在子函数内部看来thisobject 正在被继承,但我无法让它真正改变。

如果我一起删除 <Mutation/> 组件,那么一切都会按预期工作。 React-Apollo 组件或 this 对象与箭头函数交互的方式有什么特别之处吗?

import React from 'react';
import gql from 'graphql-tag'
import { Mutation } from 'react-apollo';
import { extendObservable } from 'mobx';
import { observer } from 'mobx-react';

const mutation = gql`here is a mutation`

class Why extends React.Component{

  constructor(props) {
    super(props);

    extendObservable(this, {
      text: '',
    })
  }

  onChange = e => {
    this.text = e.target.value;
  };

  render () {
    return (
      <Mutation mutation={mutation}>
      { () => (
          <div>
            {console.log(this)}
            <input  name="text"
                    placeholder="Enter Text"
                    type="text"
                    value={this.text}
                    onChange={this.onChange}/>
          </div>
        )
      }
      </Mutation>
    )
  }
}

export default observer(Why);

【问题讨论】:

    标签: javascript reactjs apollo mobx react-apollo


    【解决方案1】:

    我认为状态实际上正在改变,但组件渲染没有为您做出反应。 发生这种情况是因为 observer 组件仅跟踪由渲染函数直接访问的数据,在您的情况下,您有一个没有的函数。

    一个简单的解决方案是使用来自mobx-react&lt;Observer /&gt; 组件:

      render () {
          return (
              <Mutation mutation={mutation}>
              { () => (
                  <Observer>
                  {() => (
                       <div>
                       {console.log(this)}
                        <input  name="text"
                            placeholder="Enter Text"
                            type="text"
                            value={this.text}
                            onChange={this.onChange}/>
                       </div>
                  )}
                </Observer>
               )
             }
          </Mutation>
        )
      }
    

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 2018-10-30
      • 2019-02-11
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 2019-02-17
      • 1970-01-01
      相关资源
      最近更新 更多