1

我正在编写一个程序,以便企业可以显示他们的服务,并根据项目的大小为每个服务设置价格。在“选项”组件中,我使用了一个 useReducer(我想我必须在 useReducer 内部创建数百个“案例”,以每个服务命名)。在“服务”组件中,我使用 Formik 表单来保存传递给每个“服务”的值。

这是“选项”组件,使用 userReducer 设置价格。循环数百个服务列表以呈现数百个“服务”组件

const reducer = (state, action) => {
    switch (action.type) {
      case 'SET_SMALL_PRICE': //do I have to create hundreds of these with different ids for each?
        return {
          ...state,
          smallPrice: action.payload,
        }
      default:
        return state
    }
  }

//really long list that will be looped over
serviceList.map(item => ( 

//do I have to pass hundreds of values here, 
//one for each of the hundreds of 'Service'?
  <Context.Provider value={{ smallPrice, bigPrice }}> 
    <Service
       key={service.id}
       id={service.id}
       name={service.name}
    />)
  <Context.Provider />

“服务”组件。这些将有数百个,并且每个都需要单独设置价格(smallPrice,smallPrice2,smallPrice3 ...?)

//In case I would pass down hundreds of items through context 
//in the other component, I thought of passing each an ID 
//and then destructure these conditionally 
//like `smallPrice${props.id}`. Doesn't work unfortunately.               
const { smallPrice } = useContext(Context) 

<Formik
   initialValues={{

//gets this value through Context. also would have 
//to have ids added conditionally (through props, perhaps)
     smallPrice: smallPrice, //smallPrice1, smallPrice2 ?
   }}
   onSubmit={(values, { setSubmitting }) => {

//e.g SET_SMALL_PRICE_3 perhaps?
       dispatch({ type: 'SET_SMALL_PRICE', payload: values.smallPrice,}) 
            setTimeout(() => {
              setSubmitting(false)
            }, 400)
   }}>
       <Form>

//also change the name here so that it won't affect a different service
         <Field name="smallPrice" type="text" />
       </Form>
<Formik/>
4

0 回答 0