【发布时间】:2017-09-12 16:24:34
【问题描述】:
我有一个模态组件,它是一个弹出窗口。我需要为 bodyContainer 设置不同的组件。
<Modal
show={this.props.first.showModal}
size={this.props.first.sizeModal}
bodyContainer={this.props.first.modalBodyContainer}
/* bodyContainer={<Mail {...this.props}/>} */
onClose={this.props.firstActions.onCloseModalHome}
/>
根据我对 redux 理念的理解,我可以这样做
// Search Patient actions
export const onSearchPatient = (ur, token) => dispatch => (
callToApiWithToken(`patient/by/ur/${ur}`, token)
.then(response =>
((response.data === null) ? dispatch(onSearchPatientNotFound(ur)) : dispatch(onSearchPatientFound(response.data))),
)
.catch(error => ({ type: psActions.ON_SUBMIT_ERROR }))
);
export const onSearchPatientFound = createAction(psActions.ON_SEARCH_PATIENT_FOUND);// data
export const onSearchPatientNotFound = createAction(psActions.ON_SEARCH_PATIENT_NOT_FOUND);
//Reducer
case psActions.ON_SEARCH_PATIENT_FOUND:
return {
...state,
showModal: true,
modalBodyContainer: <PatientDetails {...action.payload} />,
};
case psActions.ON_SEARCH_PATIENT_NOT_FOUND:
return {
...state,
error: true,
errorMsg: <div>The Patient <strong>{action.payload}</strong> is not in the system</div>,
};
但我的同事认为这是一种不好的做法。具体来说我说的是
modalBodyContainer: <PatientDetails {...action.payload} />
可以将渲染逻辑重新定位到 Modal,但在这种情况下,我需要为所有可能的组件创建一个开关。
这样做的正确方法是什么?
已编辑 我有两个想法如何做到这一点。什么是最好用的?
//Action
export const setModalBody = createAction(psActions.SET_MODAL_BODY);//component
//Reducer
case psActions.SET_MODAL_BODY:
return {
...state,
showModal: true,
modalBodyContainer: action.payload />,
};
//Usage
onClick={() => searchPatient.length > 0 && onSearch(searchPatient, token).then(patientFound && setModalBody(<Patient {...props} />)
或
const Modal = ({...}) => (
{{
//Something like this
//switch based on prop.bodyComponentType
//in this case I need to import all possible components to the Modal
sectionA: (
<SectionAComponent />
),
sectionB: (
<SectionBComponent />
),
sectionC: (
<SectionCComponent />
)
}[section]}
)
已编辑 2 这不是关于 redux 操作,而是关于在 hoc 中与操作相关的组件渲染。
【问题讨论】:
-
@lux 我不这么认为。它不是关于动作,而是关于组件渲染以及如何基于 redux 哲学来实现它。如果您能提出正确的方法,请告诉我
-
不要使 body 动态,只需发出一个呈现特定模态的动作。由于您已经有了一个通用的 Modal 组件,因此无需变得聪明并更换 body。
-
@lux 所以 setModalBody 动作是个好主意,对吧?
-
这样的事情怎么样:gist.github.com/mikechabot/975eab040ca70e36bf84579453d530e5 你的 redux 操作有一个
modalType指的是一个完全构建的模态,而你只需传入该模态所需的props,而不是它的整个 DOM 主体。
标签: javascript reactjs redux react-redux