简体   繁体   中英

React/Redux, Reloading a component in route

I have the typical list of rows in a basic CRUD screen, each row, as usual with the link:

<Link to={"/appointment/"+appointment.id+"/"}>Edit</Link>

My route is:

<Route path="/appointment/:id" component={AppoModal} />

when I click "Edit" in any row a Modal dialogue appears:

在此处输入图片说明

If I do click in the first "Edit" link all works fine. But if I push the "Close" button in the dialogue and try to click any "Edit" link again, the modal dialogue is not launched, I guess this is happening because the component is already "up".

The hide/show behaviour of the dialogue is controlled by this.state.showModal value in the AppoModal component:

 constructor(props) {
    super(props);
    this.state = { showModal: true };
 }  

So I don't know how to "reload" or "re run" the component. Can I run a dispatch(action) every time I click in the "Edit" link? I heard about a "static method", but I'm too newbie with React to know if that is the path.

Thx!

The problem arises because when you click Close, you're changing the component state, but you're not changing the application state.

Since your modal opens with a route change, it should also close with a route change.

You could take a different approach and avoid the route change all together. Since you are using redux, you could have a global state which could contain a modal name as a constant or maybe contain the reference to the Component.

Now you can have a modal component that would render the component depending on the global state change and you can call this component somewhere in the root Component.

so your reducer looks like

export function modalState(state=null, action) {
  if(action.payload.name == "CLOSE_MODAL") return null;
  else if([/*modal names*/].includes(action.payload.name) {
    return {modal: action.payload.name, .data: action.payload.data}
  } else return {...state}
}

and you have an action like

export function openModal(name, data) {
  return {
    type: "MODAL_NAME",
    payload: { name, data }
}

export function closeModal() {
  return { type: "CLOSE_MODAL", payoad: null }
}

and your component could look like

const componentMaps = {
  [MODAL_1] : import MODAL_1 from "./modals/Modal_1.jsx"
}
cont Modal = React.createClass({
  render: function() {
    let Component = componentMaps[this.props.modal.name]
    if(Component) {
      return <Component {...this.props.modal.data}/>
    } else { 
      return null;
    }
  }
});

export connect(select)(Modal);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM