简体   繁体   中英

Ant Design Range Picker not updating date when state updates

I have an issue with Ant Design component: Date Picker (Range Picker). [ https://ant.design/components/date-picker/] I am using this with React and hooks. I need to be able to change the date inside of the Range Picker by clicking on the button. The data in the state is being updated properly, but it doesn't update the date in the date picker. I am thinking the issue is with the moment.js library which is being used for Date Picker by Ant Design. In the Date Picker, the date values are being enclosed inside moment functions. Maybe there is a way to update the component manually after state changes? Am I getting something wrong?

const DateSelect = () => {
  const RangePicker = DatePicker.RangePicker;
  const dateFormat = 'YYYY/MM/DD';
  const [currentDate, setCurrentDate] = useState(moment().format(dateFormat));
  const addSevenDays = () => {
  const weekFromNow = moment()
      .add(1, 'w')
      .format(dateFormat);
    setCurrentDate(weekFromNow);
    console.log(currentDate);
  };
  return (
    <div>
      <Button onClick={addSevenDays}>Add 7 days</Button>
      <RangePicker
        defaultValue={[
          moment(currentDate, dateFormat),
          moment(currentDate, dateFormat),
        ]}
        format={dateFormat}
      />
      <span> {currentDate} </span>
    </div>
  );
};
render(<DateSelect />, document.getElementById('app'));

Here is a codepen for this issue: https://codepen.io/anon/pen/rPEmPg?editors=0010

There are several mistakes you made:

  1. you don't pass an onChange callback to the DatePicker component - which means the inputs of your DatePicker will not be propagated up to the DateSelect component
  2. you are using defaultValue instead of value , which doesn't let you change the value from the parent component, when the state is updated
  3. you are saving only one date in the state, though, I suppose, you want to save a range

I've forked your codepen and fixed it: https://codepen.io/anon/pen/VgJzER

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