使用带有回调函数的Hook将<Class Component>转换为<Stateless Component>

时间:2019-07-29 06:44:27

标签: javascript reactjs react-hooks react-tsx react-jsonschema-forms

我正在尝试使用React Hooks概念将Class Component转换为Stateless Functional Component

我正在与react-jsonschema-form-Custom field components reference link

合作
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()的主体。

1 个答案:

答案 0 :(得分:0)

useState中的setter函数不接受第二个参数https://github.com/reactjs/rfcs/issues/98。我不确定您是否需要在这里使用useEffect,您可以在设置状态值后直接调用props.onChange(state)。另外请注意,您需要用新的状态值合并现有状态,因为setState将覆盖现有状态。

const onChange = name => {
    return event => {
      setState(state => {
          ...state,
          [name]: parseFloat(event.target.value)
        })
       props.onChange(state);.
    };
  };