从 React-Apollo 组件内部设置 mobX 状态
Setting mobX state from inside a React-Apollo component
尝试设置输入元素的 onChange 状态时,我无法更改状态。 React-Apollo 组件需要一个 returns 一些 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);
我认为状态实际上正在改变,但组件渲染没有为您做出反应。
发生这种情况是因为 observer
组件仅跟踪渲染函数直接访问的数据,在您的情况下,您有一个函数没有。
一个简单的解决方案是使用 mobx-react
中的 <Observer />
组件:
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>
)
}
尝试设置输入元素的 onChange 状态时,我无法更改状态。 React-Apollo 组件需要一个 returns 一些 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);
我认为状态实际上正在改变,但组件渲染没有为您做出反应。
发生这种情况是因为 observer
组件仅跟踪渲染函数直接访问的数据,在您的情况下,您有一个函数没有。
一个简单的解决方案是使用 mobx-react
中的 <Observer />
组件:
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>
)
}