export const getProductDetail = id => async dispatch => {
try {
dispatch(fetching());
const data = await ProductsService.getProductById(id);
dispatch(receiveData(data));
} catch (error) {
dispatch(fetchingError(error);
}
};
class ProductDetailContainer extends Component {
componentWillMount() {
const { match: { params: { id } }, getProductDetail } = this.props;
getProductDetail(id);
}
/* ... */
}
const mapStateToProps = state => ({
productDetail: state.products,
});
const matchDispatchToProps = {
getProductDetail,
}
export default connect(mapStateToProps, matchDispatchToProps)(ProductDetailContainer);
const fetchData = () => async dispatch => {
const data = [];
try {
while(true) {
const response = await Api.getSomeData({ from: data.length });
data.push(response.item); // если item это массив, то data.push(...response.item);
if(!response.items.length) {
break;
}
}
dispatch(fetchDataSuccess(data));
return data;
} catch (e) {
dispatch(fetchDataFail(e));
}
};
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
const Welcome ({ name }) => <h1>Hello, {name}</h1>;
addGroup = () => {
this.setState(prevState => ({ items : [ ...prevState.items, undefined ] }));
};
shouldComponentUpdate( nextProps, nextState ) {
return nextState.items !== this.state.Items;
}
shouldComponentUpdate( nextProps, nextState ) {
return nextState.items !== this.state.Items &&
JSON.stringify(nextState.items.sort()) !== JSON.stringify(this.state.items.sort());
}
fetch('https://example.com/api')
.then(response => response.json())
.then(json => dispatch(someAction(json)))
.catch(console.log);
class App extends React.Component {
state = {
category: 'business',
items: [],
};
componentDidMount() {
this.fetchData();
}
fetchData() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category='+this.state.category)
.then(res => {
this.setState({ items: res.data.articles });
});
}
changeCategory = () => {
this.setState(
{ category: 'entertainment' },
this.fetchData,
);
};
render() {
return (
<div className='wrapper'>
<button onClick={this.changeCategory}>CLICK</button>
</div>
);
}
}
Unexpected token g in JSON at position 4
const json = JSON.stringify([
{
general: { /* ... */ },
/* ... */
},
/* ... */
]);
const comments = JSON.parse(json);
{
counterReducer: 0,
}
function mapStateToProps(state) {
return {
count: state.counterReducer,
};
}
const mapStateToProps = state => ({
count: state.counterReducer,
});