Redux와의 연결을 사용하여 this.props에서 간단한 디스패치를 얻는 방법은 무엇입니까?
연결하는 간단한 React 구성 요소가 있습니다 (간단한 배열 / 상태 매핑). 스토어 컨텍스트를 참조하지 않으려면 props에서 직접 "dispatch"하는 방법을 원합니다. 나는이 접근 방식을 사용하는 다른 사람들을 보았지만 어떤 이유로 이것에 액세스 할 수 없습니다 :)
현재 사용중인 각 npm 종속성의 버전은 다음과 같습니다.
"react": "0.14.3",
"react-redux": "^4.0.0",
"react-router": "1.0.1",
"redux": "^3.0.4",
"redux-thunk": "^1.0.2"
다음은 연결 방법이있는 구성 요소입니다.
class Users extends React.Component {
render() {
const { people } = this.props;
return (
<div>
<div>{this.props.children}</div>
<button onClick={() => { this.props.dispatch({type: ActionTypes.ADD_USER, id: 4}); }}>Add User</button>
</div>
);
}
};
function mapStateToProps(state) {
return { people: state.people };
}
export default connect(mapStateToProps, {
fetchUsers
})(Users);
감속기를 볼 필요가 있다면 (흥미로운 것은 아니지만 여기 있습니다)
const initialState = {
people: []
};
export default function(state=initialState, action) {
if (action.type === ActionTypes.ADD_USER) {
let newPeople = state.people.concat([{id: action.id, name: 'wat'}]);
return {people: newPeople};
}
return state;
};
내 라우터가 redux로 어떻게 구성되어 있는지 확인해야하는 경우
const createStoreWithMiddleware = applyMiddleware(
thunk
)(createStore);
const store = createStoreWithMiddleware(reducers);
var Route = (
<Provider store={store}>
<Router history={createBrowserHistory()}>
{Routes}
</Router>
</Provider>
);
최신 정보
연결에서 내 디스패치를 생략하면 (현재 위의 fetchUsers를 표시하고 있음) 디스패치를 무료로 얻을 수 있습니다 (비동기 작업이있는 설정이 일반적으로 작동하는지 확실하지 않습니다). 사람들이 혼합하고 일치합니까, 아니면 전부입니까, 아니면 아무것도입니까?
[mapDispatchToProps]
By default mapDispatchToProps
is just dispatch => ({ dispatch })
.
So if you don't specify the second argument to connect()
, you'll get dispatch
injected as a prop in your component.
If you pass a custom function to mapDispatchToProps
, you can do anything with the function.
A few examples:
// inject onClick
function mapDispatchToProps(dispatch) {
return {
onClick: () => dispatch(increment())
};
}
// inject onClick *and* dispatch
function mapDispatchToProps(dispatch) {
return {
dispatch,
onClick: () => dispatch(increment())
};
}
To save you some typing Redux provides bindActionCreators()
that lets you turn this:
// injects onPlusClick, onMinusClick
function mapDispatchToProps(dispatch) {
return {
onPlusClick: () => dispatch(increment()),
onMinusClick: () => dispatch(decrement())
};
}
into this:
import { bindActionCreators } from 'redux';
// injects onPlusClick, onMinusClick
function mapDispatchToProps(dispatch) {
return bindActionCreators({
onPlusClick: increment,
onMinusClick: decrement
}, dispatch);
}
or even shorter when prop names match action creator names:
// injects increment and decrement
function mapDispatchToProps(dispatch) {
return bindActionCreators({ increment, decrement }, dispatch);
}
If you'd like you can definitely add dispatch
there by hand:
// injects increment, decrement, and dispatch itself
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({ increment, decrement }), // es7 spread syntax
dispatch
};
}
There's no official advise on whether you should do this or not. connect()
usually serves as the boundary between Redux-aware and Redux-unaware components. This is why we usually feel that it doesn't make sense to inject both bound action creators and dispatch
. But if you feel like you need to do this, feel free to.
Finally, the pattern you are using right now is a shortcut that's even shorter than calling bindActionCreators
. When all you do is return bindActionCreators
, you can omit the call so instead of doing this:
// injects increment and decrement
function mapDispatchToProps(dispatch) {
return bindActionCreators({ increment, decrement }, dispatch);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
can be written as this
export default connect(
mapStateToProps,
{ increment, decrement } // injects increment and decrement
)(App);
However you'll have to give up that nice short syntax whenever you want something more custom, like passing dispatch
as well.
You can usually mix and match based on what you'd like.
You can pass dispatch
on as a prop if that is what you want:
export default connect(mapStateToProps, (dispatch) => ({
...bindActionCreators({fetchUsers}, dispatch), dispatch
}))(Users);
I'm not sure how fetchUsers
is used (as an async function?), but you would usually use something like bindActionCreators
to auto-bind dispatch and then you would not have to worry about using dispatch
directly in connected components.
Using dispatch
directory sort of couples the dumb, stateless component with redux. Which can make it less portable.
While you could pass dispatch
down as part of dispatchToProps
, I would recommend avoiding accessing the store
or dispatch
directly from within your components. It seems like you would be better served by passing in a bound action creator in connect's 2nd argument dispatchToProps
See an example I posted here https://stackoverflow.com/a/34455431/2644281 of how to pass down an "already bound action creator" this way your components don't need to directly know about or depend on the store/dispatch.
Sorry to be brief. I'll update w/ more info.
'development' 카테고리의 다른 글
SQL Server 데이터베이스에서 문자열을 검색하는 방법은 무엇입니까? (0) | 2020.08.18 |
---|---|
SQLite 테이블에서 열 삭제 (0) | 2020.08.18 |
목록 요소 간의 차이점 찾기 (0) | 2020.08.18 |
'Update-Database'라는 용어는 cmdlet의 이름으로 인식되지 않습니다. (0) | 2020.08.18 |
C #의 열 이름으로 DataRow가 있는지 확인하십시오. (0) | 2020.08.18 |