[英]React/Redux: get the user geolocation using a promise and dispatch the position to the action creator
[英]Rendering modal on click (user action) react redux
我正在使用react和redux渲染模態。 我已經看到了成千上萬個有關如何創建模態的示例,但沒有一個關於如何在另一個組件中觸發它的示例。
我的商店是這樣的:
export const store=createStore(
rootReducer,
compose(
applyMiddleware(thunk)
))
以及主要組成部分:
class Main extends React.Component {
render () {
return(
<BrowserRouter>
<Provider store={store} >
<App/>
</Provider>
</BrowserRouter>
)
}}
我猜應該在app組件中渲染模態
class App extends React.Component {
render () {
return(
<div className="main-app">
<Home />
<Modal />
</div>
)
}}
但是,如何從<Home >
內部的組件中更新此Modal組件的狀態?
我的模態組件如下所示:
import LoginModal from './LoginModal';
const MODAL_COMPONENTS = {
'LOGIN': LoginModal
}
class ModalRoot extends React.Component {
render() {
const SpecificModal = MODAL_COMPONENTS[this.props.modal.modalType];
if(!this.props.modal.showModal) return <SpecificModal />
return null
}
}
let mapStateToProps=state=>{
return {
modal: state.modal
}
}
export default connect(mapStateToProps)(ModalRoot);
哪種方法是更改Redux應用程序的狀態三(存儲)以更改模式狀態的最佳方法?
謝謝
假設您想通過單擊“主頁”按鈕中的一個按鈕來觸發模態。 您可以使用mapDispatchToProps將分派函數傳遞給Home,並從那里更改模態狀態的分派動作。
actions.js
function changeModal(payload) {
return {
type: 'CHANGE_MODAL',
payload,
}
}
減速器
// below defines what's in store.modal
function modalReducer(state = {}, action) {
switch(action.type) {
case: 'CHANGE_MODAL':
return {
...state,
...action.payload
}
// ... rest of your code
}
}
家庭組件
class Home extends Component {
//... rest of logic
changeModal = (modal) => {
const currentModal = {
showModal: true,
modalType: modal,
}
this.props.changeModal({ modal: currentModal });
}
render() {
// im using 2 buttons to trigger different modals,
return <div>
<button onClick={() => this.changeModal('HOME')}>trigger home modal</button>
<button onClick={() => this.changeModal('OTHER')}>trigger other modal</button>
</div>
}
}
const mapDispatchToProps = (dispatch) => ({
changeModal: (payload) => dispatch(changeModal(payload))
});
// insert mapDispatchToProps as a second argument to connect
// home component may or may not have mapStateToProps
export default connect(mapStateToProps, mapDispatchToProps)(Home);
因此,當您按下按鈕時,state.modal將更改,並且將根據新狀態顯示模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.