() => this.someCallback()
- это сохранит эквивалентность props и React не будет лишний раз вызывать render. Напримерclass MyComponent extends React.Component {
onBtnClick = (event) => {
// correct this
};
onBtnMouseUp() {
// invalid this
}
render() {
return <button onClick={this.onBtnClick} onMouseUp={this.onBtnMouseUp}>hello</button>;
}
}
// store
const initalState = {
treesById: {},
activeByTreeId: {},
};
const treesReducer = (state, action) => {
switch (action.type) {
// store.dispatch({ type: 'ADD_TREE', id: 'users', tree: [...] })
case 'ADD_TREE':
return {
...state,
treesById: {
...state.treesById,
[action.id]: action.tree,
},
};
// store.dispatch({ type: 'SET_ACTIVE', id: 'users', value: 5 })
case 'SET_ACTIVE':
return {
...state,
activeByTreeId: {
...state.activeByTreeId,
[action.id]: action.value,
},
};
default:
return state;
}
};
// dumb component aka presenter
const Tree = ({ items, active }) => {
return (
<div className="tree-items">
{items.map((item) => (
<TreeItem
key={item.id}
item={item}
isActive={item.id === active}
/>
))}
</div>
);
};
// smart component aka container
// (state, ownProps)
const mapStateToProps = ({ trees }, { treeId }) => {
return {
items: trees.treesById[treeId] || [],
active: trees.activeByTreeId[treeId],
};
};
// use in any component, e.g. Sidebar (presenter)
// props are passed from container
const Sidebar = () => {
return (
<div className="sidebar">
<TreeContainer treeId="sidebar" />
</div>
);
};
class Foo {
onSubmit = (event) => {
// "this" is correct instance
};
}
const initalState = {
foo: 'bar',
baz: 'pew',
structure: [
['', ''],
['', ''],
],
};
const reducer = (state, action) => {
switch (action.type) {
case 'ADD_INPUT':
return {
...state,
structure: state.structure.map((v1, k1) => {
if (k1 === action.first) {
return v1.map((v2, k2) => {
if (k2 === action.second) {
return action.value;
} else {
return v2;
}
});
} else {
return v1;
}
}),
};
break;
default:
return state;
}
};
const newState = reducer(initalState, {
type: 'ADD_INPUT',
first: 0,
last: 0,
value: 'foo',
});
console.log(initalState);
console.log(newState);
const Container = connect(mapStateToProps)(App); // После этого по идее props должны попасть в App, но ничего нет
ReactDOM.render(<Provider store={store}><Container /></Provider>, document.getElementById('root')); // Рендер