美好的一天,请大家帮忙。我是昨天才开始反应的新手,我正在尝试将我以前的项目迁移到 Island Catalog 网站以使用 ASP.NETCore API 做出反应。到目前为止,我已经连接了 ASP.NET 并做出了反应,因为数据显示在控制台上,如图所示。
更新:终端发出警告“React Hook useEffect 缺少依赖项:'props'。要么包含它,要么删除依赖项数组。”怎么办?
但是,当我尝试将数据渲染到浏览器时,数据没有出现。
这是我的api.js
:
import axios from "axios";
const baseUrl = "http://localhost:49449/api/"
export default {
//baseUrl + 'dIsland'
dIsland(url = baseUrl + 'disland/'){
return {
fetchAll : () => axios.get(url),
fetchById : id => axios.get(url+id),
create : newRecord => axios.post(url, newRecord),
update : (id, updateRecord) => axios.put(url+id, updateRecord),
delete: id => axios.delete(url + id)
}
}
}
这是操作DIsland.js
:
import api from "./api";
export const ACTION_TYPES = {
CREATE : 'CREATE',
UPDATE:'UPDATE',
DELETE:'DELETE',
FETCH_ALL:'FETCH_ALL'
}
export const fetchAll = () => dispatch => {
api.dIsland().fetchAll()
.then(response => {
console.log(response)
dispatch({
type: ACTION_TYPES.FETCH_ALL,
payload: response.data
})
}
)
.catch(err => console.log(err))
}
// install material UI npm i -s @material-i/core @material-ui/icons
这是我的组件 DIslands
:
import React, {useState, useEffect } from "react";
import { connect } from "react-redux";
import * as actions from "../actions/dIsland";
//import api from "../actions/dIslands";
import { Grid, Paper, TableContainer, Table, TableHead, TableRow, TableCell, TableBody, withStyles} from "@material-ui/core";
import DIslandForm from "./DIslandForm";
const DIslands = (props) => {
useEffect(() =>{
props.fetchAllDIslands()
},[])//componentDIdMount
return(
<Paper>
<Grid container>
<Grid item xs ={6}>
<DIslandForm/>
</Grid>
<Grid item xs ={6}>
List of Islands
<TableContainer>
<Table>
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Region</TableCell>
<TableCell>Location</TableCell>
</TableRow>
</TableHead>
<TableBody>
{
props.dIslandList.map((record,index)=>{
return (<TableRow key={index}>
<TableCell>{record.Name}</TableCell>
<TableCell>{record.Region}</TableCell>
<TableCell>{record.Location}</TableCell>
</TableRow>)
})
}
</TableBody>
</Table>
</TableContainer>
</Grid>
</Grid>
</Paper>
);
//return ( <div>from Islands</div>);
}
const mapStateToProps = state =>({
dIslandList: state.dIsland.list
})
const mapActionToProps = {
fetchAllDIslands: actions.fetchAll
}
(DIslands));
export default connect(mapStateToProps, mapActionToProps)(DIslands);
这里是减速器 dIsland.js
:
import {ACTION_TYPES} from "../actions/dIsland";
const initialState = {
list:[]
}
export const dIsland = (state = initialState, action) => {
switch (action.type) {
case ACTION_TYPES.FETCH_ALL:
return {
//...state
...state,
list:[...action.payload]
}
default:
return state
}
}
答案 0 :(得分:0)
在您的情况下,这似乎是一个简单的错字。在您的 console.log 中,返回的数据包含小写的所有对象键(名称、区域等),而当您尝试检索组件中的属性时,您使用大写字母作为首字母(名称、区域、等等)。只需将其更改为:
{
props.dIslandList.map((record,index)=>{
return (<TableRow key={index}>
<TableCell>{record.name}</TableCell>
<TableCell>{record.region}</TableCell>
<TableCell>{record.location}</TableCell>
</TableRow>)
})
}
它应该可以工作。其他一切似乎都对