React中如何在组件间传递state?多组件状态传递咨询
React兄弟组件间传递State的解决方案
你的场景里,InputSection和ShortedLinks是兄弟组件,需要通过状态提升到共同父组件Testimonials来实现数据传递,具体步骤如下:
1. 改造父组件Testimonials
将shortedLink状态移到父组件中,同时引入InputSection,并把状态和更新方法通过props传递给子组件:
import { useState } from 'react'; import ShortedLinks from './ShortedLinks'; import InputSection from './InputSection'; const Testimonials = () => { const [shortedLink, setShortedLink] = useState(""); return ( <div> <InputSection setShortedLink={setShortedLink} /> <ShortedLinks shortedLink={shortedLink} /> </div> ); }; export default Testimonials;
2. 更新InputSection组件
接收父组件传递的setShortedLink方法,在API请求完成后调用该方法更新父组件的状态:
import { useState } from 'react'; const InputSection = ({ setShortedLink }) => { const [inputValue, setInputValue] = useState(""); // 模拟API请求逻辑 const handleShorten = async () => { try { // 替换为你的真实API请求 const res = await fetch(`https://your-shorten-api.com?url=${inputValue}`); const data = await res.json(); // 更新父组件的shortedLink状态 setShortedLink(data.shortUrl); } catch (err) { console.error('缩短链接失败:', err); } }; return ( <div> <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="输入原始链接" /> <button onClick={handleShorten}>生成短链接</button> </div> ); }; export default InputSection;
3. 改造ShortedLinks组件
接收父组件传递的shortedLink状态,根据状态值渲染内容:
const ShortedLinks = ({ shortedLink }) => { return ( <div> {shortedLink ? ( <div> <h3>生成的短链接:</h3> <a href={shortedLink} target="_blank" rel="noopener noreferrer">{shortedLink}</a> </div> ) : ( <h1>还未生成短链接</h1> )} </div> ); }; export default ShortedLinks;
核心逻辑说明
React遵循单向数据流,兄弟组件无法直接共享状态,因此需要将状态提升到它们的共同父组件:
- 父组件负责管理
shortedLink状态,并提供更新状态的方法 InputSection通过调用父组件的方法更新状态ShortedLinks通过props获取父组件的状态并渲染
内容的提问来源于stack exchange,提问作者Surge
相关产品推荐
相关产品推荐

