简体   繁体   中英

Stateless functional component method never gets fresh data from Redux store, but others do

I got into some trouble. I have a pretty common functional component connected to Redux via mapStateToProps:

    const TableWrapper = ({ studentsSelection }) => {

  const onComponentStateChanged = params =>
    params.api.forEachNode(node =>
      studentsSelection.selectedStudents.findIndex(student =>
        student.number === node.data.number) >= 0 &&
      node.setSelected(true)
    );

  const gridOptions = getGridOptions(onComponentStateChanged(), onSelection);

  return (
    <BootStrapTableWrapper>
      <Table gridOptions={gridOptions} />
    </BootStrapTableWrapper>
  );
};
TableWrapper.propTypes = {
  studentsSelection: PropTypes.shape({
    selectedStudents: PropTypes.array
  })
};

const mapStateToProps = state => ({
  studentsSelection: state.gpCreationWizard.studentsSelection
});

export default connect(mapStateToProps)(TableWrapper);

Where getGridOption refers to this:

const getStudentsSelectionGridOptions = (onComponentStateChanged, updateStudentsSelectionSelectionAction) => ({
    ...studentsSelectionGridOptions,
    onComponentStateChanged(props) {
        onComponentStateChanged(props);
    },
    onRowSelected({node}) {
        updateStudentsSelectionSelectionAction(node);
    },
});

export default getStudentsSelectionGridOptions;

And resulted gridOptions are used for Ag-Grid table.

So let me explain the business function: I'm using Ag-Grid table, and when user select some students, they are added to the Redux store. Then I'm using the onComponentStateChanged to keep the selection on pagination. So if user changed the page, and the old data will be replaced by new one, I want the selection to be kept when he's gonna return back. But the problem is that onComponentStateChanged is always referring to the same studentsSelection.selectedStudents (but other methods and render receiving new data). So this is probably something about js scopes. Please, what should I do to make this function be using the new data, not the old one. I tried to wrap that one in anther function, but that didn't have any effect. The funny fact, that this works fine for class component and this.props referring. If I explained that not very clear, please ask about more details.

not sure what getGridOptions does... but I think the problem is, you are calling the method instead of passing the method, so change:

const gridOptions = getGridOptions(onComponentStateChanged(), onSelection);

to:

const gridOptions = getGridOptions(onComponentStateChanged, onSelection);

so onComponentStateChanged is sent as method and not the result of calling it

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