繁体   English   中英

onClick调用提取函数时,ReactJS组件的生命周期。 状态对象在单击时消失

[英]ReactJS component lifecycle when onClick calls a fetch function. state object disappears on click

我已经在这个问题上停留了大约一个星期。 我正在尝试制作一个简单的Pokedex(当然是原始151),其右侧是直接从.json文件(从api复制)中提取的Pokemon列表,然后单击,左侧填充了该Pokemon的详细信息拿来

我的状态下有一个空对象,我想用fetch调用中的数据填充该对象:

this.state = {
    pokemonList: local,
    pokemon: {},
    name: '',
    url: '',
} 

名称和URL值直接通过onClick事件填充,然后在提取中使用URL值。

fetchSinglePokemon(event) {
        fetch(event.target.value)
            .then(response => response.json())
            .then(pokemon => console.log(pokemon))
            .then(pokemon => this.setState({ pokemon: pokemon }));
    }
setSinglePokemon(pokemon) {
        this.setState({ pokemon: pokemon });
    }     

在这两种方法运行之后,我可以在控制台中看到我想要的所有数据的json对象,但是在React DevTools中,我要覆盖的状态为空的对象从状态对象中完全删除了。 单击另一个选项将更新名称和url,但是pokemon对象将永远不会回来。

宠物小精灵是另一个没有状态的组件,可以接收所有道具。 即使只是要显示信息,该组件是否也需要是一个类?

我已经阅读了有关组件生命周期的文档中的所有内容,但找不到与我的需求相关的任何内容。

我的想法是,状态是在componentMount上设置的,而componentWillUpdate是通过onClick事件控制状态的。

我一直在尝试通过React电子书之路和Wes Bos React课程学习React,但是改变了我希望该应用程序执行的操作,以便我实际上在学习它的工作方式,而不仅仅是复制某些东西,而且这两个来源从我要去的地方分开了。

这是我回购的链接

在此先感谢您,请将其移至我错过的React学习专区。

要注意的一件事:

fetchSinglePokemon(event) {
        fetch(event.target.value)
            .then(response => response.json())
            .then(pokemon => console.log(pokemon)) <- this guy right here.
            .then(pokemon => this.setState({ pokemon: pokemon }));
    }

上面示例中标记的行将导致以下内容将pokemon设置为未定义。 response.json()解析为json对象, console.log将导致thenable解析为未定义。

可以用更好的措辞表述-但这是一种更直观的方法:

fetchSinglePokemon(event) {
        fetch(event.target.value)
            .then(response => response.json())
             //pokemon in the line below will be the json object
            .then(pokemon => console.log(pokemon))
             //pokemon in the line below will be undefined because you didn't return anything from the above block.
            .then(pokemon => this.setState({ pokemon: pokemon })); //this will look like: {pokemon:undefined}
    }

尝试这个:

fetchSinglePokemon(event) {
        fetch(event.target.value)
            .then(response => response.json())
            .then(pokemon => {
               console.log(pokemon);
               return pokemon;
             })
            .then(pokemon => this.setState({ pokemon: pokemon }));
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM