从React-Apollo组件内部设置mobX状态

时间:2018-04-10 00:23:42

标签: javascript reactjs apollo mobx react-apollo

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

如果我一起删除<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);

1 个答案:

答案 0 :(得分:2)

我认为状态实际上正在改变,但组件渲染并没有对你做出反应。 之所以会发生这种情况,是因为observer组件只跟踪渲染函数直接访问的数据,在这种情况下,你有一个不具备的功能。

一个简单的解决方案是使用<Observer />中的mobx-react组件:

  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>
    )
  }
相关问题