简体   繁体   English

按照通量模式以干净的方式将数据从react.js存储传递到组件

[英]Pass data from react.js Store to Component in a clean way following flux pattern

following the Flux pattern I'm trying to update my component and pass some values (a string and a boolean in this specific case) via the store. 按照Flux模式,我试图更新我的组件并通过商店传递一些值(在这种情况下为字符串和布尔值)。

助焊剂模式

I could not find any non-hacky way to solve this yet ie using global vars in the Store and use a getter function in the Store which is called from the component on ComponentWillMount(), not a nice solution. 我还找不到任何非hacky的方法来解决此问题,即在Store中使用全局变量并在Store中使用getter函数,这是从ComponentWillMount()上的组件调用的,不是一个很好的解决方案。

Here's a stripped down code example to show what im trying to achieve: 这是一个精简的代码示例,以显示我正在尝试实现的目标:

ExampleStore.js ExampleStore.js

import AppDispatcher from '../appDispatcher.jsx';
var displayimportError = false;
var importedID = '';
import axios from 'axios';

class ExampleStore extends EventEmitter {
  constructor() {
    super();
  }



importId(id) {
    let self = this;

    // fetch data from BE
    axios.get('foo.com').then(function(response) {
        if (response.data && response.data.favoriteEntries) {
            displayimportError = false;
        }
        self.emitChange();
    }).catch(function(error) {
        console.log(error);
        displayimportError = true;
        importedID = id;
        self.emitChange();
        // now update component and pass displayimportError and 
        // importedID.
        // best would to component.receiveUpdateFromStore(param); but 
        // it's giving receiveUpdateFromStore is not function back
      });

   }

}

var favObj = new ExampleStore();

AppDispatcher.register(function(payload) {
  var action = payload.action;
  switch (action.actionType) {
    case 'UPDATE_ID':
        favObj.importId(action.data);
        break;
}

return true;
});

export default favObj;

As mentioned in the Comment above the best solution in my eyes so far would be to call a function in the component from the store ie component.receiveUpdateFromStore(param); 就像上面的评论中提到的那样,到目前为止,我认为最好的解决方案是从商店中调用组件中的函数,即component.receiveUpdateFromStore(param);。 and then update the component state within that function but even though they seem to be im/exported correctly to me it is returning receiveUpdateFromStore is undefined. 然后更新该函数中的组件状态,即使它们似乎已正确导入/导出给我,它仍未定义receiveUpdateFromStore。

Any other idea how to solve this is appreciated. 任何其他想法如何解决这个问题表示赞赏。

//example component //示例组件

   import React from 'react';
   import ReactDom from 'react-dom';
   import ExampleStore from '../stores/ExampleStore.jsx';

   class ExampleComponent extends React.Component {


    constructor(props) {
        super(props);
    }

    receiveUpdateFromStore(param) {
        this.setState({'exampleText': param.text, 'exampleBoolean': param.bool});
    }


     render() {

        return <div className="foo">bar</div;
     }
    }
    export default ExampleComponent;

Any idea how to pass data from store to a component and update component state in a nice way? 知道如何以一种很好的方式将数据从存储传递到组件并更新组件状态吗?

I would hang your store state on the store class instance itself -- something like this.state.displayimportError = true -- and then have the component subscribe to the store: 我会将您的商店状态挂在商店类实例本身上(类似this.state.displayimportError = true ),然后让该组件订阅商店:

import React from 'react';
import ExampleStore from '../stores/ExampleStore.jsx';

class ExampleComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      importError: ExampleStore.state.displayimportError,
    };
  }

  componentWillMount() {
    ExampleStore.on( 'change', this.updateState );
  }

  componentWillUnmount() {
    ExampleStore.removeListener( 'change', this.updateState ); 
  }

  updateState = () => {
    this.setState( state => ({
      importError: ExampleStore.state.displayimportError,
    })
  }

  render() {
    return <div>{ this.state.importError }</div>
  }
}

NOTE: Above code untested, and also using class properties/methods for binding updateState . 注意:上面的代码未经测试,并且还使用类属性/方法来绑定updateState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM