我是新来的反应,并在开始粘贴时学习它。我正在构建一个小型PokemonApp,它通过PokemonAPI获取数据并将其渲染到网络上。
我通过API获取的唯一数据是口袋妖怪名称和口袋妖怪的URL。获取数据的组件称为 getDataFromAPI ,它使用axios(promises)来获取它。数据存储在 pokemoni 数组中,并显示在浏览器中。通过Crome的React Dew Tools显示的状态就是这个。
State
pokemoni: Array[20]
0: {...}
name: "metapod"
url: "http://pokeapi.co/api/v2/pokemon/11/"
1: {...}
现在我不会为所有现有对象添加一个新的[{key:value}]对,当用户点击他们获得的宠物小精灵时,它将从false变为true(它将是一个按钮或其他东西) 。用户的更改状态只会进行一次(从false到true)。
State
pokemoni: Array[20]
0: {...}
name: "metapod"
url: "http://pokeapi.co/api/v2/pokemon/11/"
havePokemon: "false"
1: {...}
我遇到的逻辑是使用.map()向所有现有对象添加新的[{key:value}]对。并且不起作用。因为我不明白这个问题。该函数位于 getDataFromAPI 组件内,名为 updatePokemon
var PokedexApp = React.createClass({
componentDidMount: function(){
this.getDataFromAPI();
},
getDataFromAPI: function(){
var that = this;
PokemonAPI.getPokemonList().then(function (temp) {
that.setState({
pokemoni: temp,
isLoading: false
});
}, function (e) {
that.setState({
isLoading: true
});
});
//This function should update the array with a new key: value pair with the name havePokemon
var updatePokemon = this.state.pokemoni.map(function(myPokemon){
myPokemon.havePokemon= "false";
return myPokemon;
});
this.setState({pokemoni: updatePokemon});
},
componentWillUnmount: function() {
this.getDataFromAPI.abort();
},
getInitialState: function() {
return{
showMyPokemon: false,
searchPokemon: '',
pokemoni: [],
isLoading: false
};
},
render: function(){
var {pokemoni, showMyPokemon, searchPokemon} = this.state;
var filteredPokemoni = PokemonLocalStorageAPI.filterPokemone(pokemoni, showMyPokemon, searchPokemon);
return (
<div>
<h1 className="text-center page-title">PokedexApp</h1>
<PokedexAppSearch onSearch={this.handleSearch} />
<PokedexAppLista pokemoni={filteredPokemoni} onToggle={this.handleToggle}/>
</div>
)
}
});
module.exports = PokedexApp;
它不起作用,我不明白为什么。如果你有时间检查我的问题,请提前Ty。