reactjs - 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
(...)
}
}
解决方案
它可以做到useState
- 这只能使用一次。请记住,您将需要使用useEffect
hook 来更改您的状态,就像您使用 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
推荐阅读
- python - 我必须在第二次迭代之前关闭一个 txt?
- amazon-s3 - 为什么 IAM 管理员在尝试将 listObjects 授予公众时收到“错误,访问被拒绝”?
- linux - 为什么进程的虚拟地址空间有漏洞
- ios - Xcode 构建设置中的“其他链接器标志”问题是什么?
- powershell - 验证默认值
- cmake - CMake / Ninja:当内容未知时递归“清理”输出目录......?
- r - R markdown ...块大小来控制knitr中的图形大小 - 文本大小问题
- azure - 如何在我的 Web 应用程序中使用 Azure AD 连接到 Azure SQL?
- arrays - copyMutableArray 和 copyMutableArray 之间的细微差别#
- python - 当我只想要 Y 和 N 时,如何错误捕获其他字母?