首页 > 解决方案 > SetState 基于带有钩子的操纵道具

问题描述

如何setState在页面加载之前使用带有挂钩的操纵道具的功能组件?

在类组件上,我会执行以下操作:

export default class Editable extends React.Component {
  constructor(props) {
    super(props)
    const {clients} = this.props

    this.state = {
      columns: [
        {title: 'test', field: 'test'},
        {
          title: 'test2',
          field: 'test'
        }
      ],
      data: clients.map((client) => ({
        test: client.test,
        test2: client.test2,
      }))
    }
  }

  render() {
    return
        (...)
     }
}

标签: reactjs

解决方案


它可以做到useState- 这只能使用一次。请记住,您将需要使用useEffecthook 来更改您的状态,就像您使用 eg 所做的那样componentWillReceiveProps

const initialColumns = [
  { title: "test", field: "test" },
  { title: "test2", field: "test" }
];

const Test = props => {
  const [columns, setColumns] = useState(initialColumns);
  const [data, setData] = useState(
    props.clients.map(client => ({
      test: client.test,
      test2: client.test2
    }))
  );

return (...)
};

只需在此处查看登录 Test.js 的控制台:https ://codesandbox.io/s/jovial-mcclintock-041qx


推荐阅读