ios - react 原生 : storage only works in simulator
<p><p>我尝试过 AsyncStorage、react-native-store 和 react-native-simple-store,它们都可以在模拟器中运行,但不能在设备上运行。我正在使用 redux 和 redux-thunk 来加载存储的状态。我在根组件的 componentDidMount 方法中调用了以下函数(使用 react-native-simple-store):</p>
<pre><code>export function loadState() {
return (dispatch, getState) => {
store.get('state').then((state) => {
if (state) {
let action = {
type: LOAD_STATE,
state: fromJS(state),
};
dispatch(action);
} else {
store.save('state', initialState);
}
}).catch((error) => {
console.log(error);
});
};
}
</code></pre>
<p>然后在我的 reducer 中,当用户触发更新时,我将在返回新状态之前更新存储中的状态,如下所示:</p>
<pre><code>case SET_UPDATED_DATE:
newState = state.set('updatedDate', action.date);
store.update('state', newState.toJS())
.catch((error) => console.log(error));
return newState;
</code></pre>
<p>初始化/更新方法是否不足?是否需要为设备进行特殊设置?或者在设备上运行时不支持 redux-thunk - main.jsbundle 或使用开发服务器 - (将日志语句放在 loadState 函数的返回函数的顶部让我相信它可能不会在设备上被调用)?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>按照 <code>AsyncStorage</code> 文档的示例,我找到了一种使其工作的方法。在我的 reducer 文件中(我的 redux 状态是一个 Immutable.js 对象):</p>
<pre><code>var STORAGE_KEY = '@AppName:state';
export function loadState() {
return async (dispatch, getState) => {
try {
var value = await AsyncStorage.getItem(STORAGE_KEY);
if (value !== null) {
dispatch(replaceState(value));
console.log('Recovered selection from disk:');
console.log(value);
} else {
saveState(JSON.stringify(initialState.toJS()));
console.log('No state on disk. Initialized with initialState.');
}
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
};
}
function replaceState(newState) {
return {
type: REPLACE_STATE,
newState: fromJS(JSON.parse(newState)),
};
}
async function saveState(state) {
try {
await AsyncStorage.setItem(STORAGE_KEY, state);
console.log('Saved selection to disk:');
console.log(state);
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
</code></pre>
<p>然后在reducer函数中:</p>
<pre><code>case SET_UPDATED_DATE:
newState = state.set('updatedDate', action.date);
saveState(JSON.stringify(newState.toJS()));
return newState;
</code></pre></p>
<p style="font-size: 20px;">关于ios -react 原生 : storage only works in simulator,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/36526974/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/36526974/
</a>
</p>
页:
[1]