简体   繁体   中英

how do refactoring one types expression in typescript and react project

i'm using typescipt in react project. but i don't know why type errors.

show me my code.

how refactoring this code plz help me

i think expression tha useTabs function args code

than useTabs return 2 values. making how return value.

i want one type that "useTabsProps" in all useTabs args and return value

Page

import React from 'react';
import useTabs from '../hooks/useTabs';

const contents = [
  {
    tab: 'tab1',
    section: 'section1'
  },
  {
    tab: 'tab2',
    section: 'section2'
  },
]

function UseTabsPage() {

  const { currentItem, changeItem } = useTabs(0, contents); // <-- contents error (Expected 1 arguments, but got 2.)

  return (
    <>
      {contents.map((content, index) => <button onClick={() => changeItem(index)}>{content.tab}</button>)}
      <div>
        {currentItem.section}
      </div>
    </>
  )
}

export default UseTabsPage;

Hooks

import { useState } from 'react';

type useTabsProps = {
  initialTab: number,
  allTabs: {
    tab: string
    section: string,
  }[]
}

function useTabs({initialTab, allTabs}:useTabsProps) {

  const [ currentIndex, setCurrentIndex ] = useState(initialTab);

  return {
    currentItem: allTabs[currentIndex],
    changeItem: setCurrentIndex
  }
}

export default useTabs;

You have simple bug in your code. Either change useTabs to

const {currentItem, changeItem} = useTabs({initialTab: 0, allTabs: contents});

or change useTabs hook props

function useTabs(initialTab: number, allTabs: Array<{ tab: string, section: string }>) {

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