Reactjs 如何从存储区或服务器获取数据?
为某些数据调用Flux store并在其存在时获取数据的最佳模式是什么 引用Facebook的Ian Obermiller的话,我在下面提到了这一点,但我找不到一个商店的例子,当请求的数据从缓存中丢失时,它有逻辑与服务器对话Reactjs 如何从存储区或服务器获取数据?,reactjs,flux,reactjs-flux,Reactjs,Flux,Reactjs Flux,为某些数据调用Flux store并在其存在时获取数据的最佳模式是什么 引用Facebook的Ian Obermiller的话,我在下面提到了这一点,但我找不到一个商店的例子,当请求的数据从缓存中丢失时,它有逻辑与服务器对话 我想在一个项目上实施这种方法,但我的团队说它打破了通量模式。有没有人有过将获取逻辑添加到存储区并将操作仅用于写入的经验?过去我这样做时,模式通常与下面的代码类似。以下是关于该代码的一些注释: getDataFromAPI()显然是一个HTTP请求或类似的东西,它返回一个承诺
我想在一个项目上实施这种方法,但我的团队说它打破了通量模式。有没有人有过将获取逻辑添加到存储区并将操作仅用于写入的经验?过去我这样做时,模式通常与下面的代码类似。以下是关于该代码的一些注释:
getDataFromAPI()
显然是一个HTTP请求或类似的东西,它返回一个承诺,并与存储中所需的数据进行解析。当然,您可以通过回调来实现这一点
storeDataInStore()
是对Dispatcher的调用,Dispatcher负责将数据存放到存储中
组件侦听存储上的更改,因此当您依次调用getDataFromAPI()
和storeDataInStore()
时,组件将侦听存储上的更改,调用handleStoreDataChange()
方法,并适当地重新渲染
import LoadingComponent from './LoadingComponent';
import Store from '../../stores/ThatStore';
import { getDataFromAPI } from '../../utils/WebUtils';
import { storeDataInStore } from '../../utils/AppUtils';
class ThisComponent extends React.Component {
constructor() {
super(props);
}
componentWillMount() {
let dataFromStore = Store.getDataFromStore();
if (/* condition indicating data is in store */) {
this.setState(dataFromStore);
} else if (/* condition indicating data is not in store */) {
getDataFromAPI().then((data) => {
storeDataInStore(data);
});
}
}
componentDidMount() {
this.handleStoreDataChange = this.handleStoreDataChange.bind(this);
Store.addChangeListener(this.handleStoreDataChange);
}
componentWillUnmount() {
Store.removeChangeListener(this.handleStoreDataChange);
}
handleStoreDataChange() {
this.setState(Object.assign(Store.getDataFromStore());
}
render() {
if (/* condition indicating that you are awaiting data */) return <LoadingComponent />;
return (
/* All of the things you would render if the data is loaded in the store */
);
}
}
import LoadingComponent from./LoadingComponent';
从“../../stores/ThatStore”导入存储;
从“../../utils/WebUtils”导入{getDataFromAPI};
从“../../utils/AppUtils”导入{storeDataInStore};
类ThisComponent扩展了React.Component{
构造函数(){
超级(道具);
}
组件willmount(){
让dataFromStore=Store.getDataFromStore();
如果(/*条件指示数据在存储器中*/){
this.setState(dataFromStore);
}如果(/*条件指示数据不在存储中*/),则为else{
getDataFromAPI()。然后((数据)=>{
存储数据存储(数据);
});
}
}
componentDidMount(){
this.handleStoreDataChange=this.handleStoreDataChange.bind(this);
Store.addChangeListener(this.handleStoreDataChange);
}
组件将卸载(){
Store.removeChangeListener(this.handleStoreDataChange);
}
handleStoreDataChange(){
this.setState(Object.assign(Store.getDataFromStore());
}
render(){
如果(/*条件表明您正在等待数据*/)返回;
返回(
/*如果数据加载到存储中,您将呈现的所有内容*/
);
}
}
hmm?