仍然习惯于使用React并正确地使用道具来绕我的头。
但是本质上我有这个react组件,我试图将“ drinkInfo”中的所有信息都使用,并使用props将其全部发送到CardInfo组件,以便在此处进行渲染。但是我得到了“未定义道具”,而且我不确定为什么。
class Render extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
// call the drinks endpoint (via axios)
let options = {
method: 'GET',
url: MYURL,
};
// let drinks = array of drinks
let drinksFromDatabase = [];
// axios request
axios.request(options)
.then( (response) => {
console.log(response);
drinksFromDatabase = response.data
console.log("Drinks from Database are:")
console.log(drinksFromDatabase)
this.setState({ drinks : drinksFromDatabase})
})
.catch(function (error) {
console.log(error);
});
}
render() {
console.log("this.state is",[this.state])
let stateArray = [this.state]
if (stateArray[0] == null) {
console.log("returning with nthing")
return <div></div>
}
let firstElement = stateArray[0];
let drinks = firstElement.drinks;
let drinkChoice = this.props.reduxState.drinkChoice
console.log("Drink Choice is: " , drinkChoice)
let drinkInfo = {
type: props.drinks.type,
name: props.drinks.name,
manufacturer: props.drinks.manufacturer,
rating: props.drinks.rating,
date: props.drinks.date,
description: props.drinks.description,
favorite: props.drinks.favorite
}
console.log("Drink info is: " , drinkInfo)
let cardComponents = drinks.map((drink) =>{
if (drink.type === drinkChoice) {
return (<InfoCard {props.drinkInfo} />)
} else {
return <div>Nothing to Report</div>
}})
return (
<div>
<div>{cardComponents}</div>
</div>
)
}
}
export default Render
您正在使用react类组件,因此您忘记添加this
来访问道具。
this.props.drinks.type
this.props.drinks.name
.....
我看到您正在将道具传递给您的组件。但是,使用ComponentDidMount()装入组件后,您将获得饮料的响应。
在ComponentDidMount()中this.SetState({drinks:DrinksFromDatabase})已初始化,因此当您console.log(drinks)时,将记录饮料状态。
您可能想重新阅读文档:
https://reactjs.org/docs/components-and-props.html
关于道具和国家。由于您设置了状态,因此需要更改:
let drinkInfo = {
type: props.drinks.type,
name: props.drinks.name,
manufacturer: props.drinks.manufacturer,
rating: props.drinks.rating,
date: props.drinks.date,
description: props.drinks.description,
favorite: props.drinks.favorite
}
至:
let drinkInfo = {
type: drinks.type,
name: drinks.name,
manufacturer: drinks.manufacturer,
rating: drinks.rating,
date: drinks.date,
description: drinks.description,
favorite: drinks.favorite
}
由于您正在使用Drinks.map(drink => {...})进行迭代,因此您可以在组件中发送每种可迭代饮料的值:
let cardComponents = drinks.map((drink) =>{
if (drink.type === drinkChoice) {
return (<InfoCard props={drinkInfo} />)
} else {
return <div>Nothing to Report</div>
}})
然后您可以从InfoCard道具中访问道具...但是说实话,DrinkInfo似乎包含与州酒相同的信息,所以我不确定为什么要创建一个对象值对象,然后可以更改前者到:
let cardComponents = drinks.map((drink) =>{
if (drink.type === drinkChoice) {
return (<InfoCard props={drinks} />)
} else {
return <div>Nothing to Report</div>
}})
这将传递您所有的饮料值,而无需创建另一个对象。希望这可以使您朝正确的方向发展。