我正在尝试使用Class Component概念将Stateless Functional Component转换为反应钩
我和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()钩子的状态更新不支持第二个回调参数。若要在呈现后执行副作用,请使用useEffect()在组件体中声明它。
发布于 2019-07-29 06:52:11
来自useState的setter函数不接受第二个参数:[钩子] useState - "setState“回调。我不确定您是否需要在这里使用useEffect,您可以在设置状态值之后调用props.onChange(state)。还要注意,您需要将现有状态与新的状态值连接起来,因为setState将覆盖现有状态。
const onChange = name => {
return event => {
setState(state => {
...state,
[name]: parseFloat(event.target.value)
})
props.onChange(state);
};
};如果确实需要确保只在对当前组件的状态设置了新值之后才调用props.onChange,则可以在useEffect中跟踪状态,同时还需要使用自定义函数进行深度比较:反应useEffect比较对象
useEffect(() => {
props.onChange(state);
}, [deepCompare(state)]) https://stackoverflow.com/questions/57248423
复制相似问题