javascript - 兑换至使用带有回调函数的 Hooks
问题描述
我正在尝试转换Class Component
为Stateless Functional Component
使用React Hooks概念
我正在使用react-jsonschema-form
-Custom field components
参考链接
const schema = {
type: "object",
required: ["lat", "lon"],
properties: {
lat: {type: "number"},
lon: {type: "number"}
}
};
// Define a custom component for handling the root position object
class GeoPosition extends React.Component {
constructor(props) {
super(props);
this.state = {...props.formData};
}
onChange(name) {
return (event) => {
this.setState({
[name]: parseFloat(event.target.value)
}, () => this.props.onChange(this.state));
};
}
render() {
const {lat, lon} = this.state;
return (
<div>
<input type="number" value={lat} onChange={this.onChange("lat")} />
<input type="number" value={lon} onChange={this.onChange("lon")} />
</div>
);
}
}
// Define the custom field component to use for the root object
const uiSchema = {"ui:field": "geo"};
// Define the custom field components to register; here our "geo"
// custom field component
const fields = {geo: GeoPosition};
// Render the form with all the properties we just defined passed
// as props
render((
<Form
schema={schema}
uiSchema={uiSchema}
fields={fields} />
), document.getElementById("app"));
我正在像这样转换上面的代码。
function GeoPosition(props) {
const [state, setState] = React.useState({ ...props.formData });
const onChange = name => {
return event => {
setState(
{
[name]: parseFloat(event.target.value)
},
() => props.onChange(state) // GETTING ERROR - UNABLE TO USE CALLBACK
);
};
};
const { lat, lon } = state;
return (
<div>
<input type="number" value={lat} onChange={onChange("lat")} />
<input type="number" value={lon} onChange={onChange("lon")} />
</div>
);
}
我认为它会引发错误,我需要使用 React.useEffect(),但不知道如何实现它。请任何反应专家支持。
index.js:1375 警告:来自 useState() 和 useReducer() Hooks 的状态更新不支持第二个回调参数。要在渲染后执行副作用,请在组件主体中使用 useEffect() 声明它。
解决方案
setter 函数useState
不接受第二个参数:[hooks] useState - "setState" callback。我不确定你需要在useEffect
这里使用,你可以props.onChange(state)
在设置状态值后调用。另请注意,您需要将现有状态与新状态值连接起来,因为这setState
会覆盖现有状态。
const onChange = name => {
return event => {
setState(state => {
...state,
[name]: parseFloat(event.target.value)
})
props.onChange(state);
};
};
如果您确实需要确保props.onChange
仅在当前组件的状态上设置了新值后才调用,您可以在 useEffect 中跟踪状态,尽管您需要使用自定义函数进行深度比较:react useEffect 比较对象
useEffect(() => {
props.onChange(state);
}, [deepCompare(state)])
推荐阅读
- php - 对多维数组进行排序未正确排序
- javascript - API 使用 JavaScript 从数据中访问某些值
- javascript - 通过 Javascript 将持久文本添加到 Div
- java - 如何防止外部类方法访问嵌套类的私有定义方法或字段?
- javascript - 如何更改更新 useState 数组中的对象
- google-cloud-storage - 从外部网站上传数据到 Cloud Storage
- mysql - 具有 x 数量的未结订单的 SQL 日期
- python - 如何修复“TypeError:'Member'对象不可下标” discord.py
- rust - 无法理解生锈寿命冲突
- r - r 使用官员包删除 xlsx 表