Javascript 如何从类组件更新功能组件的状态,以便在react中显示映射中的项
我在Gatsby JS中有一个StoreDetails功能组件,它使用UseState钩子有条件地从graphQL中的映射中呈现与状态值匹配的产品。我有一个类组件下拉菜单,当前手动填充sku'ID,它将匹配状态和映射条件语句中显示的条件。我希望下拉列表更改功能组件的状态,以便在下拉列表中选择正确的产品时显示。我一直在玩弄把状态函数作为道具来传递,但是我遇到了重新播放的问题,我被困在这里了 键位于这一行Javascript 如何从类组件更新功能组件的状态,以便在react中显示映射中的项,javascript,reactjs,react-hooks,state,gatsby,Javascript,Reactjs,React Hooks,State,Gatsby,我在Gatsby JS中有一个StoreDetails功能组件,它使用UseState钩子有条件地从graphQL中的映射中呈现与状态值匹配的产品。我有一个类组件下拉菜单,当前手动填充sku'ID,它将匹配状态和映射条件语句中显示的条件。我希望下拉列表更改功能组件的状态,以便在下拉列表中选择正确的产品时显示。我一直在玩弄把状态函数作为道具来传递,但是我遇到了重新播放的问题,我被困在这里了 键位于这一行{value.skuId===sku.skuId?当它仍在地图中时,如何根据选项下拉列表更改它
{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
}
}
}
}
}
}
}
`
从“React”导入React,{useState};
从“./组件/布局”导入布局
从“样式化组件”导入样式化;
从'@stripe/stripe js'导入{loadStripe};
//从“../components/Alert”导入警报;
从“盖茨比”中导入{navigate};
从“盖茨比图像”导入Img
const StoreHero=styled.section`
宽度:1280px;
保证金:0自动;
`
类警报扩展了React.Component{
建造师(道具){
超级(道具);
//控制台日志(道具);
this.state={test:“test”,hello:“hello1”,hash:props.hash}
}
render(){
const{test,hello,hash}=this.state
//console.log(散列);
返回(
{hash}
)
}
}
类ShowItem扩展了React.Component{
建造师(道具){
超级(道具);
this.state={value:'couch'};
this.handleChange=this.handleChange.bind(this);
}
手变(活动){
this.setState({value:event.target.value});
日志(event.target.value);
//在这里,我想更改下面value变量的状态
//根据下拉式sku选择显示正确的产品
}
render(){
返回(
sku_拥有1kusbv3gpgw
sku_HACMgLjJBZFR7A
);
}
}
类产品扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
条纹:空
};
this.loadStripeLib=this.loadStripeLib.bind(this);
this.handleSubmit=this.handleSubmit.bind(this);
}
componentDidMount(){
this.loadStripeLib()
}
异步loadStripeLib(){
试一试{
常量条带=等待加载条带(“pk_测试_随机”);
this.setState({stripe});
}抓住{
//无所事事
}
}
handleSubmit(sku、productId){
返回事件=>{
event.preventDefault();
this.state.stripe.redirectToCheckout({
项目:[{sku,数量:1}],
成功URL:`http://localhost:8000/store/${productId}#成功`,
取消URL:`http://localhost:8000/store/${productId}#已取消`,
}).然后(函数(结果){
//向客户显示result.error.message
控制台错误(结果);
});
}
}
render(){
const{id,currency,price,name,productId}=this.props
常量价格浮动=(价格/100).toFixed(2)
const formattedPrice=Intl.NumberFormat('en-US'{
风格:“货币”,
货币,
}).格式(价格浮动)
返回(
{name}({formattedPrice})
立即购买
)
}
}
const StoreDetails=({data,location})=>{
const[value,setValue]=useState({
skuId:“sku_拥有1kusbv3gpgw”
});
//console.log(值);
返回(
{/* */}
{data.alldatocmstore.edges.map({node:sku})=>(
{value.skuId===sku.skuId?
:
无效的
}
))}
)
}
导出默认存储详细信息
export const query=graphql`
查询storedetailsquery($slug:String!){
ALLDATOCMSTORE(筛选器:{productId:{eq:$slug}){
边缘{
节点{
价格
产品ID
臭鼬
标题
身份证件
形象{
固定的{
…盖茨比达托固定
}
}
}
}
}
allStripeSku{
边缘{
节点{
身份证件
通货
价格
属性{
名称
}
形象
本地文件{
childImageSharp{
固定(宽度:125){
…盖茨比
}
}
}
}
}
}
}
`
看起来我把它复杂化了,我还有更多的事情要做,但是把它改成这个,我就可以解决这个问题了
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>
)
}
conststoredetails=({data,location})=>{
const[value,setValue]=useState({
skuId:“sku_拥有1kusbv3gpgw”
});
常量运行=(事件)=>{
console.log(事件);
setValue({skuId:event})
}
返回(
{/* */}
{data.alldatocmstore.edges.map({node:sku})=>(
{value.skuId===sku.skuId?
运行(event.target.value)}>
sku_拥有1kusbv3gpgw
sku_HACMgLjJBZFR7A