我有一个问题列表表与reactjs我有一个工作的代码和不工作的部分。我想从api中获取数据,并添加一个数组来列出组件,这些组件已经设计好了,它的道具都是真的。
让我解释一下:
代码片段:
import './App.css';
import React,{useState,useEffect} from 'react';
import {Container, Row} from 'reactstrap';
import Login from './components/Login';
import MainPage from './MainPage';
import WorkersPage from './WorkersPage';
import Schedule from './components/Schedule';
import Createrequest from './components/Createrequest';
import Jobrequests from './components/Jobrequests';
function getLocalObject(y)
{
var x;
x=localStorage.getItem(y);
return JSON.parse(x);
}
let array=[]
let requestArray=[]
function App() {
const [profile,setProfile]=useState('');
const [username,setUsername]=useState('');
const [requestedJobName,setRequestedJobName]=useState('');
const [requests,setRequests]=useState([]); //this is for requests
const [message,setMessage]=useState('')
const [password,setPassword]=useState('');
const [logout,setLogout]=useState(0);
const [allJobs,setAllJobs]=useState([]); //this is for all jobs
//This is for all jobs
useEffect(() => {
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("http://localhost/scheduleapp/api/schedule/all", requestOptions)
.then(response => response.text())
.then(result => {
setAllJobs(JSON.parse(result))
console.log('rs',result,'ls',allJobs)
})
.catch(error => console.log('error', error));
}, [])
// This is for requests (only admins!)
useEffect(() => {
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("http://localhost/scheduleapp/api/schedule/admin/requests", requestOptions)
.then(response => response.text())
.then(result => {setRequests( JSON.parse(result))})
.catch(error => console.log('error', error));
}, [])
function exit()
{
localStorage.clear()
window.location.reload(true);
}
//login function
const login = () => {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Access-Control-Allow-Origin","*");
myHeaders.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
var raw = JSON.stringify({username, password});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
//dsaasd
fetch("http://localhost/scheduleapp/api/personals/login", requestOptions)
.then(response => response.text())
.then(data =>{
localStorage.setItem('Logged',data);
})
.catch(error => console.log('error', error));
window.location.reload();
}
if(!getLocalObject('Logged'))
{
return( <div> <Login onSubmit={(e)=>e.preventDefault(e)} username={(e)=>setUsername(e.target.value)} password={(e)=>setPassword(e.target.value)} OnClick={()=>login() } /></div>
)
}
else{
if(getLocalObject('Logged').is_admin==1)
{
function accept()
{
}
function decline()
{
}
return (
<div>
{allJobs.map(item=>{
return (<Schedule approved_job_name={item.approved_job_name} approved_job_unique_id={item.approved_job_unique_id} approved_job_worker={item.approved_job_worker} date={item.date} />
)//it works great
} )
}
{
requests.map( item=>{
return(
<Jobrequests id={item.id}/>
)// this gives 'TypeError: requests.map is not a function'
} )
}
<button onClick={exit} className='btn btn-danger'>LogOut</button>
</div>
);
}
else{
function sendRequest()
{
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"requestedJobName": requestedJobName,
"uniquejobid": requestedJobName+Date.now(),
"username": getLocalObject('Logged').username
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://localhost/scheduleapp/api/schedule/worker/addrequest", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
return (
<div className='ms-4 mt-4'>
<Createrequest onSubmit={(e)=>e.preventDefault()} onChange={(e)=>setRequestedJobName(e.target.value)} onClick={sendRequest} />
{allJobs.map(item=>{
return (
<Schedule approved_job_name={item.approved_job_name} approved_job_unique_id={item.approved_job_unique_id} approved_job_worker={item.approved_job_worker} date={item.date} />
)
})}
<button onClick={exit} className='btn btn-danger'>LogOut</button>
</div>
);
}
}
}
export default App;
我想如果登录用户是admin用户将看到作业请求和所有作业所有作业被列出成功,但请求给出错误"映射不是一个功能"致以最亲切的问候由于从现在…
编辑:Console Log Outputs:
useEffect(() =比;{fetch("http://localhost/scheduleapp/api/schedule/admin/requests"不要犹豫(反应=比;setRequests (response.json ()))
}, [])
输出:请求[]
useEffect(() =比;{fetch("http://localhost/scheduleapp/api/schedule/admin/requests"不要犹豫(反应=比;setRequests (response.json ()))}, [])
Output:
req
Promise {<fulfilled>: {…}}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
id: "1"
request_job_current_date: "2021-10-05"
request_job_name: "sdasdads"
request_job_unique_id: "sdasdads1633453239"
request_job_worker_uname: "dariustheone"
[[Prototype]]: Object
自requests
初始状态是一个数组只有一个setRequest
,你的问题是来自数据传递到
.then(result => {setRequests( JSON.parse(result))})
检查result
中的内容,并且您调用。text()而不是。json(),因为您使用JSON.parse.
但无论如何,你的问题是来自result
的内容,这似乎不是一个数组
我认为你应该确保获取请求'/scheduleapp/api/schedule/admin/requests'返回一个数组后,你解析它。当您尝试映射非数组的内容时,会发生错误。
你的问题来自requests
'数组类型被你的useEffect()
改变了。
我建议这样做:
fetch("http://localhost/scheduleapp/api/schedule/admin/requests", requestOptions)
.then(response => response.json())
.then(data => setRequests(data))
只要你的console.log(requests)
不显示适当的array
(你的似乎是一个对象),那么你的问题将持续存在。
注:由于GET
是fetch
的默认方法,我认为在requestOptions
上指定它是没有必要的。