javascript - 如何在 ReactJS 中的功能组件之间传递值 - 输出 [object Object]/undefined?
问题描述
我无法在同一个 .js 文件中的功能组件中传递道具。我之前尝试过发布此问题,但没有任何帮助。
我想member_id
从我的第一个函数中的 GET 请求中获取,并在我的第二个函数中GetMemID
使用它来设置member_id
我的 useState Transactions
。
我知道我的 GET 请求正在运行,因为我可以在检查代码后看到数据。
到目前为止,使用我的代码,当我member_id
在Transactions
.
到目前为止,这是我的代码:
import React, { useEffect, useState } from 'react';
import { Redirect } from 'react-router-dom';
import moment from 'moment';
import HomeNavBar from '../components/HomeNavBar.js';
var currentDate = moment().format("MM/DD/YYYY HH:mm:ss");
function GetMemID() {
const [details, setDetails] = useState([]);
const [error, setError] = useState(null);
const options = {
method: 'GET',
headers: {
'Content-type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
'Authorization': `JWT ${localStorage.getItem('token')}`
}
};
useEffect(() => {
fetch("http://########/api/members/get/", options)
.then(response => {
if (response.status !== 200) {
console.log(response.status);
setError(response);
}
response.json().then(data => {
setDetails(data);
});
});
}, []);
return (
<div className="App">
{details.map(item => (
<Transaction member_id={item.member_id} />
))}
</div>
);
}
function Transaction({member_id}) {
//props.state
const [error, setError] = useState(null);
const [trans, setTrans] = useState({member_id:member_id, category:'', description:'', amount:0});
const [details, setDetails] = useState({id:0, mmeber_id:0, group:"", username:""});
console.log("member_id: " + member_id);
//GET rerquest to get transaction memberID
const options = {
method: 'GET',
headers: {
'Content-type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
'Authorization': `JWT ${localStorage.getItem('token')}`
},
};
useEffect(() => {
fetch("http://########/api/members/get/", options)
.then(response => {
if (response.status !== 200) {
console.log(response.status);
setError(response);
}
response.json().then(data => {
setDetails(data);
});
});
}, []);
//POST request to API for transaction
const optionPOST = {
method: 'POST',
headers: {
'Content-type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
'Authorization': `JWT ${localStorage.getItem('token')}`
},
body:JSON.stringify(trans)
}
const createTransaction = e => {
e.preventDefault();
fetch("http://########/api/transactions/post/", optionPOST)
.then((response) => console.log('reponse: ' + response.json()))
.then((message) => console.log('message: ' + message))
}
if (error) {
return (<Redirect to="/Signin" />);
} else{
return (
<div className="wrapper">
<HomeNavBar />
<form>
<div className="form-horizantal">
<fieldset>
<div className="form-group row">
<label className="col-md-12"><p>{currentDate}</p></label>
</div>
<div className="form-group row">
<label className="col-md-12">
<p>Member ID</p>
<input type="text" name="member_id" defaultValue={trans.member_id} readOnly/>
</label>
</div>
<div className="form-group row">
<label className="col-md-12">
Select Category
</label>
</div>
<div className="form-group row">
<label className="col-md-12">
<select value={trans.category} onChange={e => setTrans({ ...trans, category: e.target.value })} >
<option value=""></option>
<option value="billsutilities">Bills/Utilities</option>
<option value="groceries">Groceries</option>
<option value="health">Health</option>
<option value="transportation">Transportation</option>
<option value="ehoppingentertainment">Shopping/Entertainment</option>
<option value="mics.">Mics.</option>
</select>
</label>
</div>
<div className="form-group row">
<label className="col-md-12">
<p>Description</p>
<input type="text" name="description" value={trans.description} onChange={e => setTrans({ ...trans, description: e.target.value })} />
</label>
</div>
<div className="form-group row">
<label className="col-md-12">
<p>Amount</p>
<input type="text" name="amount" value={trans.amount} onChange={e => setTrans({ ...trans, amount: e.target.value })} />
</label>
</div>
</fieldset>
<button type="submit" onClick={createTransaction}>Submit</button>
</div>
</form>
</div>
);
}
}
export default Transaction;
解决方案
const [isLoading,setIsLoading] = useState(false)
useEffect(() => {
fetch("http://########/api/members/get/", options)
.then(response => {
if (response.status !== 200) {
console.log(response.status);
setError(response);
}
response.json().then(data => {
setDetails(data);
setIsLoading(true);
});
});
}, []);
return (
<div className="App">
{isLoading && details.map(item => (
<Transaction member_id={item.member_id} />
))}
</div>
可能的解决方案是 -> 1 ) 因为我在上面的代码示例中使用了 isLoading 状态,它最初是 false 并在从 API 加载数据时设置为 true。并有条件地渲染事务组件。2)为了更清楚地调试它,记录状态详细信息的值(以确保我们正确获取数据),像这样->
useEffect(()=>{
console.log(details);
},[details])
- 还要检查 JSON 数据的所有键是否来自 API 并正确输入。
如果它对您有用,请分享您的评论。干杯!
推荐阅读
- amazon-web-services - 在 AWS ec2 上连接 Jupyter notebook 时如何解决“PermissionError: [Errno 13] Permission denied”?
- java - 传递给 CompletableFuture.allOf() 的所有期货都会运行吗?
- c# - 为什么复合控件点击事件不触发?
- python - 如何在python生成器中运行所有斐波那契数
- twilio - 从代理服务直接切换到 Studio Flow 时,Flex 与 SMS 的集成不起作用
- java - 在 ArrayList 中检索已更改对象的索引的方法?
- react-native - 如何在 react-native-gifted-chat 中将消息从子输入传递到父聊天
- android - 如何用 Retrofit2 和 ArrayList 解析?
- visual-studio-code - 使用链接的css文件在html文件中没有ctrl +空格的VS Code自动完成
- angular - 为柱形图设置点宽时,highchart 响应问题