【问题标题】:Access Redux Store in List of ReactElements访问 ReactElements 列表中的 Redux Store
【发布时间】:2021-01-12 03:00:16
【问题描述】:

我有一个这样的列表:

const form = [
    <Input title="What is your age?" onSubmit={} />, // this onSubmit sets age
    <MultipleChoice title="What is the weather today?" onSubmit={} />, // this onSubmit sets weather
    <Input title="What is the brand of your rain coat?" onSubmit={} /> // this onSubmit sets rainCoatBrand
]

注意:上面的列表没有在 React 组件中定义。我也有这样的店:

age: number;
weather: string;
rainCoatBrand: string;

对于form 中的每个元素,如何设置onSubmit 方法以使用我想要的值更新存储?谢谢!

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    您可以使用 store.dispatch() 从 React 组件外部实现此目的。请注意,要使其正常工作,您需要在某处定义 reducers 以处理分派的操作并相应地更新存储。

    import { store } from './storepath';
    
    const form = [
        <Input 
           title="What is your age?" 
           onSubmit={() => store.dispatch({ // redux action payload })} 
        />, 
        <MultipleChoice 
           title="What is the weather today?" 
           onSubmit={() => store.dispatch({ // redux action payload })} 
        />
        <Input 
           title="What is the brand of your rain coat?" 
           onSubmit={() => store.dispatch({ // redux action payload })} 
        /> 
    
    ]
    

    要从输入中获取实际值,您需要自己修改输入组件来处理这个问题。

    例如

    export const MultipleChoice = (props) => {
       const [value, setValue] = useState();
    
       ...
       
       return <div title={props.title} onSubmit={() => props.onSubmit(value)}/>
    }
    
    const form = [
       <MultipleChoice 
           title="What is the weather today?" 
           onSubmit={(payload) => store.dispatch({ type: 'UPDATE_WEATHER', payload })} 
        />,
        ...
    ]
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 2018-05-17
      相关资源
      最近更新 更多