如何从类组件更新功能组件的状态,以便在 react 中显示映射中的项目



我在Gatsby JS中有一个StoreDetails函数组件,它使用UseState钩子从graphQL中的映射有条件地渲染与状态值匹配的产品。我有一个类组件下拉菜单,目前手动填充了与状态和映射条件语句中显示的条件匹配的 sku'id。我希望下拉列表更改功能组件的状态,以便在下拉列表中选择正确的产品时显示正确的产品。我正在尝试将状态函数作为道具传递,但我遇到了重新渲染问题,卡在这里。

关键在此行{value.skuId === sku.skuId ?当选项下拉列表仍在地图中时,如何根据选项下拉列表进行更改

提前致谢

这是我到目前为止的代码


import React, {useState} from 'react';
import Layout from "../components/layout"
import styled from 'styled-components';
import {loadStripe} from '@stripe/stripe-js';
// import Alert from '../components/Alert';
import { navigate } from "gatsby";
import Img from "gatsby-image"


const StoreHero = styled.section`
width:1280px;
margin:0 auto;
`
class Alert extends React.Component{
constructor(props){
super(props);
//console.log(props);
this.state = {test:"test",hello:"hello1",hash:props.hash}
}
render(){
const { test, hello, hash } = this.state
//console.log(hash);
return(
<div>{hash}</div>
)
}
}

class ShowItem extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
console.log(event.target.value);
// Right here is where I want to change the state of the value variable below so
// that the correct product is shown based on the dropdown sku selection
}

render() {

return (
<select value={this.state.value} onChange={this.handleChange}>
<option value="sku_HAD1kUsbV3GpgW">sku_HAD1kUsbV3GpgW</option>
<option value="sku_HACMgLjJBZFR7A">sku_HACMgLjJBZFR7A</option>
</select>

);
}
}
class Product extends React.Component{
constructor(props) {
super(props);
this.state = {
stripe: null
};
this.loadStripeLib = this.loadStripeLib.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
this.loadStripeLib()
}
async loadStripeLib() {
try {
const stripe = await loadStripe('pk_test_random');
this.setState({ stripe });
} catch {
// do nothing
}
}
handleSubmit(sku, productId){
return event => {
event.preventDefault();
this.state.stripe.redirectToCheckout({
items: [{sku, quantity: 1}],
successUrl: `http://localhost:8000/store/${productId}#success`,
cancelUrl: `http://localhost:8000/store/${productId}#cancelled`,
}).then(function (result) {
// Display result.error.message to your customer
console.error(result);
});
}
}

render(){
const { id, currency, price, name, productId } = this.props
const priceFloat = (price / 100).toFixed(2)
const formattedPrice = Intl.NumberFormat('en-US', {
style: 'currency',
currency,
}).format(priceFloat)
return(
<form onSubmit={this.handleSubmit(id, productId)}>
<h2>
{name} ({formattedPrice})
</h2>
<button type="submit">Buy Now</button>
</form>
)
}
}
const StoreDetails = ({data, location}) =>{
const [value, setValue] = useState({
skuId: "sku_HAD1kUsbV3GpgW"
});

//console.log(value);

return(
<Layout>
<StoreHero>
<Alert test="test" hello="hello" hash={location.hash}/>
{/* <ShowItem props={data}/> */}                                    
{data.allDatoCmsStore.edges.map(({ node: sku }) => (
<>
{value.skuId === sku.skuId ?
<>
<ShowItem setValue={setValue}/>
<Product
key={sku.id}
id={sku.skuId}
productId={sku.productId}
currency="cad"
price={sku.price}
name={sku.title}
/>
<Img fixed={sku.image.fixed}/>
</>
:
null
}
</>
))}
</StoreHero>
</Layout>
)
}
export default StoreDetails
export const query = graphql`
query StoreDeatailsQuery($slug: String!)  {
allDatoCmsStore(filter: {productId: {eq: $slug}}) {
edges {
node {
price
productId
skuId
title
id
image{
fixed{
...GatsbyDatoCmsFixed
}
}
}
}
}
allStripeSku {
edges {
node {
id
currency
price
attributes {
name
}
image
localFiles {
childImageSharp {
fixed(width: 125) {
...GatsbyImageSharpFixed
}
}
}
}
}
}
}
`

看起来我把它复杂化了,我还有很多事情要做,但将其更改为这个为我修复了它

const StoreDetails = ({data, location}) =>{
const [value, setValue] = useState({
skuId: "sku_HAD1kUsbV3GpgW"
});

const run = (event) =>{
console.log(event);
setValue({skuId:event})
}

return(
<Layout>
<StoreHero>
<Alert test="test" hello="hello" hash={location.hash}/>
{/* <ShowItem props={data}/> */}                                    
{data.allDatoCmsStore.edges.map(({ node: sku }) => (
<>
{value.skuId === sku.skuId ?
<>
<select onChange={(event) => run(event.target.value)}>
<option value="sku_HAD1kUsbV3GpgW">sku_HAD1kUsbV3GpgW</option>
<option value="sku_HACMgLjJBZFR7A">sku_HACMgLjJBZFR7A</option>
</select>
{/* <ShowItem setValue={setValue}/> */}
<Product
key={sku.id}
id={sku.skuId}
productId={sku.productId}
currency="cad"
price={sku.price}
name={sku.title}
/>
<Img fixed={sku.image.fixed}/>
</>
:
null
}
</>
))}
</StoreHero>
</Layout>
)
}

React UI 将通过对状态更改做出反应来更改。 如果两个子组件需要相同的数据(在本例中为所选值)。 那么所选值的状态应该在父组件上(在StoreDetails中),因此当StoreDetails的值状态被作为 props 发送到onChange的函数更改时,Product将发生变化。

最新更新