如何使用带有Typescript的Axios为Formik设置初始值

时间:2020-01-30 13:41:43

标签: reactjs axios formik

我是使用React,Formik和Axios的新手,并且不确定如何从数据库调用中设置表单的初始值。我已经尝试了下面的代码片段,但是没有成功。我无法在线找到任何打字稿示例,以了解如何执行此操作。

async function getInitialValues() {
      try {
            const response = await axios.get('http://localhost:53132/api/test');
            //console.log(response);


            return {
                Division_Id: response.Divison_Id,
                Year: response.Year,
                Cost: response.Cost
            }

            //console.log(InitialValues);

            //return InitialValues;


          } catch (error) {
            console.error(error);
          }
    }


<Formik initialValues={getInitialValues()}...

2 个答案:

答案 0 :(得分:1)

您将要在安装时发出网络请求(在此示例中使用“ useEffect”钩子)。然后将这些值保存为状态(使用此处的useState挂钩,但是您可以使用Redux或使用的任何状态管理工具)。

function NewForm() {
  const [initialValues, setInitialValues] = useState();

  useEffect(() => {
    getInitialValues().then(res => setInitialValues(res);
  }, []);

  return initialValues ? 
    <Formik initialValues={initialValues}>content</Formik> :
    <span>loading...</span>;
}

答案 1 :(得分:0)

那是因为您缺少useEffect中的依赖项。如果您只想在页面渲染时运行一次,则将一个空数组添加为依赖项(useEffect的第二个参数)

let data = [
  {id: 10939, reference_id: 1, name: "A", value: "A", children: {
    1002: {id: 22, reference_id: 22, name: "A!", value: "A1"},
    1013: {id: 23, reference_id: 23, name: "A2", value: "A2"}
  }},
  {id: 10940, reference_id: 2, name: "B", value: "B", children: {
    1014: {id: 33, reference_id: 33, name: "B1", value: "B1"}
  }},
  {id: 10941, reference_id: 3, name: "C", value: "C", children: {
    IN01: {id: 44, reference_id: 44, name: "C1", value: "C1"},
    IN02: {id: 41, reference_id: 42, name: "C2", value: "C2"},
    IN03: {id: 55, reference_id: 22, name: "A!", value: "A1"},
    IN04: {id: 55, reference_id: 55, name: "G2", value: "G2"}
  }}
];
let result=[];
data.reduce((_,b)=>{
for(key in b.children){ result.push(b.children[key])}});
console.log(result);