问题描述
我正在尝试在 React 的另一个组件中渲染组件。 我不明白为什么在获取完成后 optionwrapper 不呈现。 如果有人能解释为什么它不起作用,那就太完美了
在商店我有这个
import { observable,makeObservable,action,computed,toJS,configure } from 'mobx';
configure({
useProxies: "never"
})
class MainStore {
options = new Object;
constructor() {
makeObservable(this,{
options: observable,setoptions: action,getoptions: computed,})
}
setoptions() {
fetch(http)
.then((response) => response.json())
.then((data) => {
this.options = data
console.log(this)
})
.catch(error => console.log(error))
}
get getoptions() {
return toJS(this.options);
}
}
const GlobalStore = new MainStore;
export default GlobalStore;
我不知道为什么它不起作用
解决方法
我认为您应该使用观察者包装 SearchResults 组件
const SearchResults =observer(() => {
useEffect( () => {
GlobalStore.setOptions();
},[]);
return(
<div className={styles.column}>
{
GlobalStore.getOptions.result=='OK' &&
<OptionWrapper options={ GlobalStore.options.data.body} />
}
</div>
)})
,
import React,{useState} from 'react';
import { withScriptjs,withGoogleMap,GoogleMap,InfoWindow } from "react-google-maps";
import MarkerWithLabel from "react-google-maps/lib/components/addons/MarkerWithLabel";
import styles from './MyMapComponent.module.css';
import GlobalStore from '../../../stores/MainStore';
import { observer } from 'mobx-react';
const MyMapComponent = withScriptjs(withGoogleMap(observer((props) => {
const icon = {
url: " ",scaledSize: new google.maps.Size(0,0)
};
const [flag,setFlag] = useState(false);
return(
<GoogleMap
defaultZoom={11}
defaultCenter={{lat: props.Markers.searchResults.results[0].coordinate.lat,lng: props.Markers.searchResults.results[0].coordinate.lon}}
>
{props.isMarkerShown && props.Markers &&
props.Markers.searchResults.results.map((val,index)=>(
<MarkerWithLabel
position={{ lat: val.coordinate.lat,lng: val.coordinate.lon }}
key={val.thumbnailUrl}
labelAnchor={new google.maps.Point(0,0)}
icon = {icon}
title={val.id.toString()}
onClick={(e)=>{
GlobalStore.setPropertySelected(e);
setFlag(!flag);
}}
>
<div className={GlobalStore.propertySelectedId == val.id ? styles.marker_label_selected : styles.marker_label}>
{val.ratePlan.price.current}
</div>
</MarkerWithLabel>
))
}
{/* я пытался использовать переменную из mobx,но тогда не работает */}
{flag &&
<InfoWindow
position={ {lat: GlobalStore.propertySelected.coordinate.lat,lng: GlobalStore.propertySelected.coordinate.lon} }
onCloseClick={()=>setFlag(!flag)}
>
<div className='styles.rap'>
<img src={GlobalStore.propertySelected.thumbnailUrl}/>
<h6>{GlobalStore.propertySelected.ratePlan.price.current}</h6>
<h5>{GlobalStore.propertySelected.address.streetAddress}</h5>
<h6>Rating: {GlobalStore.propertySelected.guestReviews.rating}</h6>
</div>
</InfoWindow>
}
</GoogleMap>
) })
))
export default MyMapComponent ;
这就是我解决问题的方法。 正如你所看到的,我使用了观察者,但没有帮助