通过 API 调用设置表单的初始值

Sky*_*ell 7 reactjs formik react-hooks

在我的 React 游戏中,我使用名为 Formik 的 React 库作为表单。

在其中,您可以像这样设置表单的初始值:

<Formik
    initialValues={{
        characterClasses: ["1", "3", "9"],
        race: "Elf",
        name: "Derolt",
        age: "84",
        
        ..etc
        
Run Code Online (Sandbox Code Playgroud)

但现在,我想要从 API 调用加载初始值。

所以我创建了这个:

const fetchGameCharData = async (gameId) => {
    const game = await axios("api/games/" + gameId);
    // return the result
    return game;
};
Run Code Online (Sandbox Code Playgroud)

我的问题是,我不知道如何使用上面的 fetch 方法来实际填充 Formik 使用的initialValues 部分。

有人这样做过吗?

谢谢!

Pra*_*ddy 7

使用条件渲染方法。

仅在收到 API 调用的响应后才加载表单。显示loading...或自定义,spinner直到获得 API 响应。

通过这种方法,您的表单可以直接加载,而initial values不会出现首次加载时没有值的闪烁,并且由于 API 响应,值会在闪存中出现。

编辑

// In your state add two values like
initialValues: [],
isValueLoded: false

...

// Make your API call in `componentDidMount`
componentDidMount() {
    // Call your API
    fetchGameCharData(....).then(res => {
        this.setState({ isValueLoded: true, initialValues: res.values});
    }).catch(err => ....);
}

....

// In your render method
render() {

    return !this.state.isValueLoded ?
       (<div>Loading...</div>) : (
        <Formki
          values={this.state.initialValues}
         ....
         />
    );
}
Run Code Online (Sandbox Code Playgroud)