如何从子组件中设置父组件中的变量



我有一个父组件。它是情态动词。我试图从一个子组件,即ShippingBlock更新一个变量。我正在尝试更新shippingMethod.

import React from 'react';
import "./Checkout.scss"
import AddressBlock from './AddressBlock';
import PaymentBlock from './PaymentBlock';
import ShippingBlock from './ShippingBlock';
import TotalsBlock from './TotalsBlock';
import { Modal, ModalHeader, ModalBody } from 'reactstrap';
class CheckoutModal extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'React'            
};
}    

render() {
let shippingMethod = null;
function setShippingMethod(method) {
shippingMethod = method;
}
const buttonStyles = {
position: "absolute",
top: "-35px",
right: "10px",
border: "0",
background: "none"
};        
return (
<Modal id="checkout"
isOpen
size='xl'>
<button onClick={this.props.onRequestClose} style={buttonStyles}>x</button>
<ModalHeader className="header">
Checkout                    
</ModalHeader>
<ModalBody>                    
<div className="row">
<AddressBlock />
<ShippingBlock setShippingMethod={setShippingMethod} shippingMethod={shippingMethod}/>
</div>
<div className="row">
<PaymentBlock />                    
<TotalsBlock />
</div>
</ModalBody>
</Modal>
);
}
}
export default CheckoutModal;
import React from 'react';
import Config from 'config';
import "./Checkout.scss"
class ShippingBlock extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'React',
shippingMethods: [],
defaultMethod: this.props.shippingMethod
};
}
async componentDidMount() {
console.log('Running componentDidMount')
const tokenString = sessionStorage.getItem("token");
const token = JSON.parse(tokenString);
let headers = new Headers({
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer ' + token.token
});
const response = await fetch(Config.apiUrl + `/api/Shipping/GetShippingMethods`, {
method: "GET",
headers: headers
});
const json = await response.json();
console.log(json);
this.setState({ shippingMethods: json });
if (this.state.defaultMethod === null) {
const mresponse = await fetch(Config.apiUrl + `/api/Users/GetDefaultShippingMethod`, {
method: "GET",
headers: headers
});
const mjson = await mresponse.json();
console.log(mjson);
this.setState({ defaultMethod: mjson });
}        
}
setShippingMethod(e) {
console.log('Shipping method ' + JSON.stringify(e.target.value));
this.props.setShippingMethod(e.target.value);        
this.state.defaultMethod = e.target.value;        
}
render() {
const shippingMethods = this.state.shippingMethods;
const defaultMethod = this.state.defaultMethod;        
return (
<aside id="checkout" className="block col-1">
<h1>Shipping</h1>
<div className="row">
<select id="comboMethod" onChange={this.setShippingMethod.bind(this)} value={defaultMethod === null ? null : defaultMethod.trim()}>
{shippingMethods.map(method => { return <option key={method.shipmthd.trim()} value={method.shipmthd.trim()}>{method.shipmthd.trim()}</option>} )}
</select>
</div>
</aside>
);
}
}
export default ShippingBlock;

每当我尝试更改ShippingBlock中的select时,我的功能onChange运行并且控制台日志显示正确的选择值,但不知何故该值被设置回默认值。我还不能准确地指出我做错了什么。如有任何提示或帮助,我将不胜感激。

import React from 'react';
import "./Checkout.scss"
import AddressBlock from './AddressBlock';
import PaymentBlock from './PaymentBlock';
import ShippingBlock from './ShippingBlock';
import TotalsBlock from './TotalsBlock';
import { Modal, ModalHeader, ModalBody } from 'reactstrap';
class CheckoutModal extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'React',
shippingMethod: null
};
}    
setShippingMethod(method) {
this.state.shippingMethod = method;
}
render() {
const buttonStyles = {
position: "absolute",
top: "-35px",
right: "10px",
border: "0",
background: "none"
};        
return (
<Modal id="checkout"
isOpen
size='xl'>
<button onClick={this.props.onRequestClose} style={buttonStyles}>x</button>
<ModalHeader className="header">
Checkout                    
</ModalHeader>
<ModalBody>                    
<div className="row">
<AddressBlock />
<ShippingBlock setShippingMethod={this.setShippingMethod.bind(this)} shippingMethod={this.state.shippingMethod}/>
</div>
<div className="row">
<PaymentBlock />                    
<TotalsBlock />
</div>
</ModalBody>
</Modal>
);
}
}
export default CheckoutModal;

这是我以前的。它的行为是一样的。

你做错的是shippingMethod不是父组件状态的一部分。

您已经在渲染函数中定义了它,该函数在每次呈现父组件时运行。这意味着你在那里设置的值将重置回它在子组件渲染之前的值,即null,因此子组件在渲染时将获得null

解决方案将变量移到父类的状态,并使setter成为父类的成员。


您的setShippingMethod应该使用this.setState(类似于功能组件中的useState钩子):

setShippingMethod(method) {
this.setState(state => ({...state, shippingMethod: method}));
}

相关内容

  • 没有找到相关文章

最新更新