【问题标题】:Couldn't save data to local storage in React无法将数据保存到 React 中的本地存储
【发布时间】:2021-12-25 16:53:07
【问题描述】:

我正在使用 React 构建电子商务,其中有一个包含不同货币的下拉菜单。货币来自包含所有信息的 GraphQL 端点。当用户选择一种货币时,它会更改列出的价格。这是由上下文实现的,我在货币选择器组件中使用该上下文。所有这一切都很好,但是,当我从一开始就启动网络时,什么都没有显示,因为没有默认货币保存。我正在尝试将下拉菜单中的第一种货币保存到本地存储并将其设置为上下文,但这对我没有任何作用。请让我知道您建议这样做吗?

我将在下面附上货币选择器组件和货币上下文的代码。

CurrencyContext.js

    export const CurrencyContext = createContext()

class CurrencyContextProvider extends Component {

    state = {selectedCurrency: 'uiu'}
    setCurrency = (c)=>{
        this.setState({selectedCurrency: c})
    }

    render() {
        return (
            <CurrencyContext.Provider value={{...this.state, setCurrency: this.setCurrency}}>
                {this.props.children}
            </CurrencyContext.Provider>
        )
    }
}

export default CurrencyContextProvider;

CurrencySelector.js

    export class CurrencySelector extends React.Component{

    constructor(props) {
        super(props)
        this.state = { currencies: [] }
    }

    async componentDidMount(){
        let currencies = (await this.getCurrencies()).data.currencies
        this.setState({ currencies:currencies } )
    }

    async getCurrencies(){
        return await fetchTheQuery( `query{ currencies }` )
    }

    render() {
        return (
            <CurrencyContext.Consumer>
                {(currencyContext) => {
                    const {setCurrency} =currencyContext
                    return(
                        <select name="currency-selector"
                                onChange={event => {
                                        setCurrency(event.target.value)
                                        localStorage.setItem("currency", event.target.value)
                                }}>
                            {this.state.currencies.map(
                                (currency, index) => {
                                    return (
                                        <option value={currency}>
                                            {currency}
                                        </option>
                                    )
                                }
                            )}
                        </select>
                    )
                }}
            </CurrencyContext.Consumer>
        )
    }
}

【问题讨论】:

  • @Andy 你能告诉我吗?
  • @Andy 顺便说一句,我正在使用一个类组件 idk 是否可以使用它
  • 是的,对不起,我完全错过了。
  • 你在哪里从 localstorage 获取状态?
  • @programoholic 数据在getCurrencies() in CurrencySelector.js 下获取

标签: javascript reactjs react-context


【解决方案1】:

onChange 中的函数是否可能当前没有运行?

也许您可以将传入onChange 的函数隔离到一个名为handleChange 的类函数中。

【讨论】:

  • onChange 运行良好。我的问题是将默认货币存储到上下文中。因此,当您从一开始就启动网络时,默认货币必须显示在屏幕上。如果有不清楚的地方请告诉我
【解决方案2】:

如果我正确理解您的问题,您需要在 API 返回数据之前在选择框中加载默认值。当GraphQL API 收到响应时,您还希望将用户选择的先前值保留为选定值。这是您可以执行的操作: 在contextProvider从localStorage加载默认值如下:

function getDefaultValue() {
  const currency = localStorage.getItem('currency');
  return currency ? currency : 'USD';
}
const defaultVal = getDefaultValue(); //Insert the default value here.
export const CurrencyContext = createContext();
class CurrencyContextProvider extends Component {
  constructor(props) {
    super(props);
    this.state = { selectedCurrency: defaultVal }; // initial value in state
    this.setCurrency = this.setCurrency.bind(this);
  }
... rest of the code

现在消费者将收到selectedCurrency,默认值是从localStorage 填充的。

现在在消费者中,您需要检查和切换黑白选项:

      {currencies.length
        ? currencies.map((currency, index) => {
            return <option value={currency}>{currency}</option>;
          })
        : // render the default currency from context when currency is not loaded
          [selectedCurrency].map((currency, index) => {
            return <option value={currency}>{currency}</option>;
          })}

您还需要使用selectedCurrency 在选择时设置value 属性。

这是工作示例:Stackblitz Demo

P.S : 您应该考虑将整个代码移至功能组件并使用useContext 挂钩。

【讨论】:

  • 感谢您的回复。但默认货币必须是我从端点获得的数组中的第一个货币
  • 你在回复中得到了吗?
  • 是的,我从端点的响应中得到了所有的货币
  • 你检查过这个例子吗?
  • 选择框会被默认选中。
猜你喜欢
  • 2014-07-07
  • 1970-01-01
  • 2018-07-14
  • 2023-03-19
  • 2023-03-15
  • 1970-01-01
  • 2018-11-17
  • 2019-01-03
相关资源
最近更新 更多