我有一个 App.jsx,声明一个常量和 setState 例程。我将 setState 放入函数(update_word_list)中。我将该函数传递给子组件。 console.log 将 typeof 参数打印为“function”,并且函数本身的打印显示该函数在子组件中被解释。 该函数不执行。
我是 JavaScript 新手。如果我做了一些愚蠢的事情,我深表歉意(不用说......)。
下面有很多代码,所以我希望这描述了 WordsSample.jsx 中问题的本地化。概述/总结行动: App.jsx:
function **Update_Word_List** (word_list) { console.log("Update word list inside app.js + word_list") setWord_List(word_list={word_list}) return (word_list) }
WordsSample.jsx
function SendSample( props ) {
console.log("Props value: " + typeof(props.dowords))
console.log("Props value: " + props.dowords)
周边代码:
import './App.css';
import ControlS from './Controls'
import WordSample from './WordsSample'
import List_Words from './List_Words';
import {useState, useEffect} from 'react'
function App() {
const [word_list, setWord_List] = useState(["1", "2"])
function update_word_list (word_list) {
console.log("Update word list inside app.js + word_list")
setWord_List(word_list={word_list})
return (word_list)
}
useEffect (() => {
<App />
}, []);
return (
<div className="App">
<ControlS />
<WordSample word_list={word_list} dowords={()=>update_word_list}/>
<List_Words word_list={word_list}/>
Word_Sample 子组件。笔记: Word_sample 中的按钮使用 props 调用函数 sendSample。
import React, {useEffect, useState} from 'react';
import endPoints from './api';
import axios from 'axios';
export default function WordSample(props) {
let [sample, setWordSample] = useState("")
useEffect(() => {
loadSample()
}, [])
const loadSample = async () => {
const data = await endPoints.sample();
setWordSample(sample=data)
}
function sendSample( props ) {
console.log("Props value: " + props.dowords)
let send = {}
send['words'] = sample
axios.defaults.headers.post['Access-Control-Allow-Origin'] = "*";
axios.post('/genwords', send, {
headers: {
'Content-Type': 'application/json',
}
}).then(res => {
// console.log("Response words:" + JSON.stringify(res.data))
let strwords = JSON.stringify(res.data)
strwords = strwords.split(",")
props.dowords(strwords)
console.log("In theory we have done the function" + props.word_list)
// word_list.forEach((word, i)=>console.log(word))
}).catch(err=>console.log("Error found: " + err))
return(
<>
<h2>Literal</h2>
</>
)
}
return (
<div className="wordsample">
<div className="ctlheader">
<h1>Word Sample</h1>
</div>
<p>Type (or paste) the word sample that you would like to generate sci-fi names from</p>
<form id="form" method="POST">
<textarea placeholder={sample} id="word" name="words" required
onChange={(e)=>setWordSample(sample=e.target.value)}></textarea>
<br />
<button type="submit" onClick={()=>sendSample(props)} name="genwords" id="genword">Names</button>
</form>
</div>
)
}
各位,
我已经破解了这个 - 并不完全令我满意。很简单,我直接传递setState函数:
我想我很困惑:
所以仍然有些神秘。如果我触底的话我会更新。现在:感谢您的善意帮助,我不想让其他人花时间在这上面。特别感谢https://stackoverflow.com/users/5053002/jaromanda-x!!