如何从另一个文件更新反应组件的状态?

How to update a react component's state from another file?

在我的应用程序中,我有一个文本和一个列表,它们使用 react-virtualized 来呈现大量项目列表,每个项目都有关于文本中某些单词的详细描述。效果很好,但我需要的是当我点击文本中的某个区域时,重新渲染列表以便显示相应的项目

class VirtualizedList extends Component{
  constructor(props) {
    super(props);
    this.state = {
      scrollToIndex: 0
    };
    this.renderItem = this.renderItem.bind(this);
    this.scrollToIndex = this.scrollToIndex.bind(this);
  }

renderItem ({
  key = this.props.data[index].key,
  index,
  parent,
  style,
  itemToRender = this.props.data[index]
}) {
  return (
    <CellMeasurer 
    cache={cache}
    columnIndex={0}
    key={key}
    parent={parent}
    rowIndex={index}
  >
      <div
        style={style}
      >
        {index}
        {itemToRender}
      </div>

      </CellMeasurer>
  )
}
scrollToIndex(index) {
    this.setState({
      scrollToIndex: index
    });
}

render() {    

return (      
  <AutoSizer>
      {
        ({ width, height }) => (
          <List
            width={width}
            height={height}
            rowCount={this.props.data.length}
            deferredMeasurementCache={cache}
            rowHeight={cache.rowHeight}
            rowRenderer={this.renderItem}
            scrollToIndex={this.state.scrollToIndex}
          />          
        )
      }
      </AutoSizer>
);
}
};

export default VirtualizedList;

在它的父级中是这样称呼的:

<VirtualizedList
    data={listItems} >     
</VirtualizedList>

我创造了 滚动到索引() 方法,以便我可以调用它并更新 VirtualizedList 的状态,从而将列表重新呈现到指定的索引,但我收到此警告: setState(...): 只能更新一个已挂载或挂载的组件...

我这样调用方法(滚动列表以包括第 10 项):

const listInstance = new VirtualizedList;
      listInstance.scrollToIndex(9);

任何有关如何实施此功能的帮助或建议,我们将不胜感激。 谢谢!

const listInstance = new VirtualizedList; listInstance.scrollToIndex(9);

你不能这样做 - 这不是同一个实例,不是 rendered/mounted 等

你需要lift state up - 由家长沟通。

只需从父级传递 scrollToIndex 作为 prop:

<VirtualizedList
  data={listItems}
  scrollToIndex={someSelectedIndexInParent}
/>

您可以使用 PureComponent

class VirtualizedList extends PureComponent{

它将在道具更改时重新渲染。

当然在<List

中使用this.props
scrollToIndex={this.props.scrollToIndex}