const Foo = ({ data }) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(func(data));
}, [data]);
return (/* ... */);
}
componentDidMount() {
setTimeout(() => {
updateStore(1); // <--- WTF?
});
}
import React, { useRef, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { Provider, connect } from 'react-redux';
import { createStore } from 'redux';
const UPDATE = 'UPDATE';
const update = (payload) => ({
type: UPDATE,
payload,
});
const reducer = (state = 0, action) => {
if (action.type === UPDATE) {
return action.payload;
}
return state;
}
const store = createStore(reducer);
const mapStateToProps = state => ({ state });
const mapDispatchToProps = { update };
const Header = ({ state }) => (
<div>Header. State: {state}</div>
);
const ConnectedHeader = connect(mapStateToProps)(Header);
const Body = ({ state, update }) => {
const inputEl = useRef(null);
const handler = useCallback(() => {
update(inputEl.current.value);
}, [inputEl, update]);
return (
<div>
<div>Body. State: {state}</div>
<input type="number" ref={inputEl} />
<button onClick={handler}>Update state</button>
</div>
);
}
const ConnectedBody = connect(
mapStateToProps,
mapDispatchToProps,
)(Body);
const App = () => (
<Provider store={store}>
<ConnectedHeader />
<ConnectedBody />
</Provider>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
yarn add react-redux
устанавливает стабильную, рекомендованную к использованию версию пакета.const mapDispatchToProps = {
fetchOnePhone,
};
componentDidMount() {
const { phonestoreService, match, fetchOnePhone } = this.props;
const { id } = match.params;
fetchOnePhone(phonestoreService, id);
}
fetchOnePhone(id);
let cart = [];
// сумму тут хранить не надо
const initCart = () => {/* ... */};
const addProduct = (product, quantity) => {/* ... */};
const deleteProduct = id => {/* ... */};
const changeQuantity = (id, quantity) => {/* ... */};
const addProduct = (product, quantity) => {
const index = cart.indexOf(item => item.product.id = product.id);
if (index !== -1) {
cart = cart.map((item, i) =>
i === index ? { ...item, quantity: item.quantity + quantity } : item);
} else {
cart = [ ...cart, { product, quantity} ];
}
const sum = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
localStorage.setItem('cart', JSON.stringify(cart));
localStorage.setItem('sum', JSON.stringify(sum));
return dispatch => {
dispatch({
type: ADD_PRODUCT,
payload: {
cart,
sum,
},
});
};
}
if (index !== -1) {
cart[index].quantity += quantity;
} else {
cart.push({ product, quantity });
}
{
product,
quantity,
}
export function* fetchPostBySlugSaga({ payload: { slug } }) {
try {
const data = yield call(Api.fetchPostBySlug, slug);
yield put(fetchPostBySlugSucceeded(data));
} catch (error) {
yield put(fetchPostBySlugFailed(error));
}
}
export default function* watchFetchPostBySlugSaga() {
yield takeLatest(FETCH_POST_BY_SLUG, fetchPostBySlugSaga);
}
export function fetchPostBySlug(slug) {
return {
type: FETCH_POST_BY_SLUG,
payload: {
slug,
},
};
}
export function fetchPostBySlugSucceeded(data) {
return {
type: FETCH_POST_BY_SLUG_SUCCEEDED,
payload: {
data,
},
};
}
export function fetchPostBySlugFailded(error) {
return {
type: FETCH_POST_BY_SLUG_FAILED,
payload: {
error,
},
};
}
export default reduxForm({ validate })(ChatForm);
<ChatForm form={name} />
const mapStateToProps = (state, ownProps) => ({
form: ownProps.name,
});
export default compose(
connect(mapStateToProps),
reduxForm({ validate }),
)(ChatForm);
<ChatForm name={name} />
export default function reducer(state = {}, action) {
import search from "./search-reducer";
const initialState = {
value: "",
works: [],
};
export default function search(state = initialState, action) {
function defaultEqualityCheck(a, b) {
return a === b
}
handleSearchChange = (e, { value }) => {
this.setState({ filter: value });
};
const results = data.filter(item => item.title.toLowerCase().includes(filter.toLowerCase()));
getUsers = () => {
const { dispatch } = this.props;
fetch(`https://api.github.com/search/users?q=Donetsk`)
.then(res => res.json())
.then(res => {
return Promise.all(
res.items.map(user => fetch(`https://api.github.com/users/${user.login}`).then(res => res.json()))
).then(users => {
dispatch({ type: 'GET_USERS', users });
});
});
};
class Example extends React.Component {
componentDidMount() {
const { fetchComments, productSlug } = this.props;
fetchProductCommentsBySlug(productSlug);
}
handleRemoveComment = id => {
this.props.removeProductCommentById(id);
};
handleSubmitComment = e => {
// ...
this.props.postProductComment(productComment);
};
render() {
const { comments, users } = this.props;
// ...
}
}
const mapStateToProps = state => ({
users: usersSelector(state),
comments: commentsSelector(state),
});
const mapDispatchToProps = {
fetchProductCommentsBySlug,
removeProductCommentById,
postProductComment,
};
connect(mapStateToProps, mapDispatchToProps)(Example);