状态道具被插件道具覆盖

时间:2017-07-17 11:15:25

标签: reactjs mobx mobx-react

这里的组件包含

class Submit extends Component {
    constructor(props) {
        super(props)
        this.props.appState.recipes = JSON.parse(localStorage.getItem("recipes")) || []
    }

    submitForm() {
        debugger //I also get props properly here.
        this.props.appState.recipe.name = this.name.value
        this.props.history.push('/home')
    }

    onImageDrop(files) {
        debugger //props overridden by Dropzone props :( appState is undefined
        this.props.appState.uploadedFileCloudinaryUrl = files[0]
    }
    render() {
        return (
         <form onSubmit={() => this.submitForm()}>
            <Dropzone
                multiple={false}
                accept="image/*"
                onDrop={this.onImageDrop}>
                <p>Drop an image or click to select a file to upload.</p>
            </Dropzone>...
        )
    }
}

export default Submit

我可以在构造函数和表单的提交方法(submitForm())中访问mobx道具但是如果我将文件上传到Dropzone并检查“onImageDrop()”函数中的props内容我不会重新认识任何属性。好的经验丰富的反应开发人员有意义,但我无法理解为什么它覆盖我自己的状态道具以及我如何解决它?

1 个答案:

答案 0 :(得分:1)

绑定问题。在构造函数中预绑定onImageDrop(这是首选方式)

constructor(props) {
    super(props)
    this.submitForm = this.submitForm.bind(this)
    this.onImageDrop = this.onImageDrop.bind(this)

    this.props.appState.recipes = JSON.parse(localStorage.getItem("recipes")) || []
}

或使用箭头功能,就像您对submitForm

所做的那样
render() {
    return (
     <form onSubmit={() => this.submitForm()}>
        <Dropzone
            multiple={false}
            accept="image/*"
            onDrop={files => this.onImageDrop(files)}>
            <p>Drop an image or click to select a file to upload.</p>
        </Dropzone>...
    )
}
相关问题