ユーザーが状態を変更したときにAPIデータからページデータを取得する方法があります(これにはreact-route-dom
を使用)。いくつかのページには、より多くのデータを取得するために2回目のajax呼び出しが必要な属性があります。私が抱えている問題は、変数が二次情報で更新されていないことです。私は「なぜ」を理解するが、それを解決する方法は理解していない。ReactJSでajax呼び出し後の変数を更新していますか?
//page data gets pulled into a state and passed to a child component "page.js"
//gets archive attribute
var isArchive = customMeta.isArchive;
//gets the archive target name
var archiveName = customMeta.archiveName;
//sets the initial value (mostly for debugging)
var worksArchive = "hello world";
//checks if value exists and that it is an archive
if(isArchive && isArchive == "true"){
//only get the archive info if the name is also present
if(customMeta.archiveName) {
//make the ajax call to get the data for the archive pages
axios.get('http://admin.datasite.co/v2/'+archiveName)
.then((response) => {
var archivePages = response.data;
//if the archive is "works" then create a list of archive pages
if(archiveName == "works"){
//run a loop for each page returning a link that passes through a history router
worksArchive = archivePages.map(function(work){
return <Link key={work.id} className="work-item" to="/" ><img src={work.post_meta.targetimg} /></Link>;
});
}
})
.catch((error) => {
console.log(error);
});
}
}
...
{worksArchive} //this always outputs "hello world"
...
私はアヤックスとmap
を通じてconsole.log
EDをしましたし、すべてがエラーなしで正しいです。私はを知っています問題は、ドームが描かれた後に再び値が設定されるため、私はその変更が見られないのです。私は彼らの方法は状態としてこれを保存することですが、どのように問題を解決するか分からない。
'としたときに可変使用' this.setStateを設定({worksArchive:archivePages.map ....}) 'また、あなたはコンストラクタで初期状態を設定する必要があります: '' –