首页 > 解决方案 > 如何将 this.setState({ [section]: y }) 转换为 useState 钩子?

问题描述

我只是将我的类转换为函数组件。我想在一个函数中转换为状态。

constructor() {
    super();
    this.state = {
      sections: [1, 2, 3, 4, 5, 6, 7, 8],
      currentSection: 1
    };
  }
onItemLayout = ({ nativeEvent: { layout: { x, y, width, height } } }, section) => {
    // setting each items position
    
     this.setState({ [section]: y });
    
  };

我刚刚将状态转换为

const [sections] = useState([1, 2, 3, 4, 5, 6, 7, 8]);
const [currentSection, setCurrentSection] = useState(1);

但无法理解如何转换

this.setState({ [section]: y });

到功能组件。

标签: reactjsreact-nativereact-hooks

解决方案


const [state, setState] = useState({
   sections: [1, 2, 3, 4, 5, 6, 7, 8],
   currentSection: 1
});

const onItemLayout = ({ nativeEvent: { layout: { y } } }, section) => {
   setState(currentState => ({
      ...currentState,
      [section]: y
   }))
};

const updateSection = (newSection) => {
   setState(currentState => ({
      ...currentState,
      currentSection: newSection
   }))
};

推荐阅读