我希望将数据从单个API显示到不同的组件,因为我只想点击API一次,并将数据分发给多个小组件。我知道我可以通过使用redux状态来完成这个任务,但是我不知道该如何做。需要你的帮助才能实现这一点。下面是到目前为止完成的代码。
homepage/index.js
import SlidingBanner from './banner/BannerList';
import Celebslider from './celebrityslider/CelebSlider';
class HomePage extends Component {
render() {
return (
<div>
<SlidingBanner />
<anotherslider />
</div>
);
}
}
export default HomePage;BannerList.js
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { itemsFetchData } from '../../../actions/items';
class BannerList extends Component {
componentDidMount() {
this.props.fetchData();
}
render() {
let bannerArray = [];
let banner = this.props.items.banner
for (let key in banner) {
bannerArray.push(banner[key]);
return (
<div>
<Slider {...slidersettings}>
{this.props.items.banner.map((item) => (
<div key={item.id}>
<img src={item.image_url} className="img-responsive"/>
</div>
))}
</Slider>
</div>
);
}
if (this.props.hasErrored) {
return <p>Sorry! There was an error loading the items</p>;
}
if (this.props.isLoading) {
return <p>Loading…</p>;
}
return (null);
}
}
BannerList.propTypes = {
fetchData: PropTypes.func.isRequired,
items: PropTypes.object.isRequired,
hasErrored: PropTypes.bool.isRequired,
isLoading: PropTypes.bool.isRequired
};
const mapStateToProps = (state) => {
return {
items: state.items,
hasErrored: state.itemsHasErrored,
isLoading: state.itemsIsLoading
};
};
const mapDispatchToProps = (dispatch) => {
return {
fetchData: (url) => dispatch(itemsFetchData(url))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(BannerList);anotherslider.js
Now in this file, i want to fetch another array of objects or object from the same API.
I tried to mount the API in container component but did not worked, I hope i am doing some mistake. Please correct. 发布于 2018-11-28 07:51:36
如果您想在两个滑块中调用数据,您有两种方法来处理它。
HomePage.js组件中进行redux请求,并将数据绑定到其他组件。BannerList.js组件上的数据时,您的状态将被更新。只需将redux连接添加到您的anotherslider.js组件中,并在更新时获取数据。
const mapStateToProps = (state) => {返回{ items: state.items,hasErrored: state.itemsHasErrored,isLoading: state.itemsIsLoading };};导出默认连接(mapStateToProps,mapDispatchToProps)(HomeList);发布于 2018-11-28 07:45:31
如果您想要在anotherslider.js文件中获取数据,您必须将还原器连接到其中的类/函数,以及在BannerList.js文件中进行连接。现在,在呈现调用componentWillReceiveProps(nextProps)函数之前,您将在这里获得数据。
发布于 2018-11-28 09:02:25
除了所有这些选项之外,您还可以使用react的上下文API作为提供者/使用者,在小型组件之间分发数据.这将节省您将道具传递给所有小型组件,并使用Context.Consumer直接访问组件中的值。此外,如果您不想将此状态存储在全局redux存储中,则上下文API会将您从它中保存下来.
https://stackoverflow.com/questions/53514309
复制相似问题